将计数选择为多列

时间:2014-09-20 16:30:19

标签: sql-server

我有一张这样的表

MonthYear  JobType   JobID
01-2014    FullTime  1
01-2014    PartTime  2
02-2014    FullTime  3
03-2014    FullTime  4
04-2014    PartTime  5
04-2014    PartTime  6
04-2014    FullTime  7

我想选择按MonthYear分组的每种作业类型的计数,如下所示。

MonthYear  FullTime  PartTime
01-2014    1         1
02-2014    1         0
03-2014    1         0
04-2014    1         2

有谁能建议如何实现这一目标? 感谢。

2 个答案:

答案 0 :(得分:2)

SELECT MonthYear,
SUM(CASE WHEN JobType='FullTime' THEN 1 ELSE 0 END) as FullTime ,
SUM(CASE WHEN JobType='PartTime' THEN 1 ELSE 0 END) as PartTime
FROM t
GROUP BY MonthYear

答案 1 :(得分:0)

枢轴解决方案:

SELECT
  [MonthYear],
  [FullTime],
  [PartTime]
FROM 
 (values
  ('01-2014', 'FullTime',1),
  ('01-2014', 'PartTime',2),
  ('02-2014', 'FullTime',3),
  ('03-2014', 'FullTime',4),
  ('04-2014', 'PartTime',5),
  ('04-2014', 'PartTime',6),
  ('04-2014', 'FullTime',7)) x(MonthYear, JobType, JobID)
PIVOT (count(JobType)  
for JobType
in([FullTime],[PartTime])  
)as p 
ORDER BY MonthYear