我有一个包含5个不同记录的SQL表,并且都有id:
ID Name
1 New
2 SomeWhatNew
3 KindOfNew
4 Old
5 Dead
我需要将ID 1,2和3组合在一起(给它们命名为New_Results),这样我就可以计算它们。
所以我要说我有五个1和4个2和一个3和6个4和两个5。 所以我的结果将是:
Name Count
New_Results 10
Old 6
Dead 2
如何编写可以执行此操作的tsql查询?
感谢您的帮助。
答案 0 :(得分:1)
您可以使用case
表达式:
select (case when id in (1, 2, 3) then 'New_Results'
else Name
end) as grp
from t
group by (case when id in (1, 2, 3) then 'New_Results'
else Name
end);
答案 1 :(得分:0)
SELECT
(CASE WHEN ID IN(1,2,3) THEN 'New_Results' ELSE NAME END) AS Name,
COUNT(*) AS Count
FROM df1
GROUP BY CASE WHEN ID IN(1,2,3) THEN 'New_Results' ELSE NAME END
以下是fiddler 链接。
答案 2 :(得分:0)
虽然您可以使用案例陈述,但我发现他们可以减慢您的查询速度。如果您期望大量数据或者只是想比较性能,请尝试使用联合:
鉴于您的ID和Name列位于名为“type_table”的表中,并且数据位于名为“results_table”的表中,并且type_table.id和results_table.type_id之间存在关系:
SELECT
'New_Results' AS Name,
COUNT( 1 ) AS Count
FROM
results_table
WHERE
type_id BETWEEN 1 AND 3
UNION
SELECT
type_table.Name,
COUNT( 1 ) AS Count
FROM
results_table
JOIN type_table
ON results_table.type_id = type_table.id
WHERE
type_table.id > 3
答案 3 :(得分:0)
declare @t table(ID int,Name varchar(40))
insert into @t VALUES
(1,'New'),
(1,'New'),
(1,'New'),
(1,'New'),
(1,'New'),
(2,'SomeWhatNew'),
(2,'SomeWhatNew'),
(2,'SomeWhatNew'),
(2,'SomeWhatNew')
,(3,'KindOfNew')
,(4,'Old')
,(5,'Dead')
,(5,'Dead')
;with CTE as
(
select ID,DENSE_RANK()over( order by id)rn
,case when id in(1,2,3) then 'New_Results' when id=4 then 'Old' else 'Dead' end Name
from @t t1
)
select
count(*),Name
from CTE
group by Name