在没有join和pivot的单个select语句中聚合数据

时间:2017-08-16 09:44:42

标签: sql-server sql-server-2008 tsql

我有一个表Input_Table定义如下

create table Input_Table(id int, [year] varchar(100),initial int,final int)

   insert into Input_table values(1,'2017',1,11)
   insert into Input_table values(2,'2017',8,11)
   insert into Input_table values(3,'2017',3,33)
   insert into Input_table values(4,'2016',6,44)
   insert into Input_table values(5,'2016',6,44)
   insert into Input_table values(6,'2017',6,44)
   insert into Input_table values(7,'2016',4,8)
   insert into Input_table values(8,'2017',2,8)

我需要根据图片中显示的要求获取输出,而不使用pivot或JOIN enter image description here

3 个答案:

答案 0 :(得分:3)

您可以使用条件聚合:

SELECT 'Change from ' + cast(t.initial as varchar(20)) + ' to ' + cast(t.final as varchar(20)) as [data],
       COUNT(case when t.year = 2017 THEN 1 END) as [2017],
       COUNT(case when t.year = 2016 THEN 1 END) as [2016]
FROM input_table t
GROUP BY t.initial,t.final

答案 1 :(得分:1)

您可以使用group by expression来获得如下查询

之类的结果
  select 
    'change from ' + cast(initial as varchar(100))+ ' to ' + cast(final as varchar(100)) as data,
    sum(case when year=2017 then 1 else 0 end) [2017], 
    sum(case when year=2016 then 1 else 0 end) [2016] 
from Input_Table
group by 'change from ' + cast(initial as varchar(100))+ ' to ' + cast(final as varchar(100))
order by 1

Live demo

答案 2 :(得分:1)

您可以根据GROUP BY列使用SUM和条件year

 SELECT
      'Change from ' + CAST(initial AS varchar) + ' to ' + CAST(final AS varchar) AS [Data],
      SUM(CASE WHEN [year] = '2017' THEN 1 ELSE 0 END) AS [2017],
      SUM(CASE WHEN [year] = '2016' THEN 1 ELSE 0 END) AS [2016]
   FROM
      Input_Table
   GROUP BY
      initial,
      final
   ORDER BY
      [Data];