SQL Query按名称计算唯一服务和组

时间:2012-11-10 10:07:48

标签: sql sql-server tsql

我对SQL很新,我被困在一个查询上。我有下表Appointment

NAME    SERVICE DATE
-----------------------------    
John    Abc 2012-11-10
Michael Xyz 2012-11-10
Denis   Xyz 2012-11-10
Denis   Pqr 2012-11-06
John    Abc 2012-11-06
Michael Abc 2012-11-05
Sofy    Abc 2012-11-04
John    Pqr 2012-11-01
Michael Pqr 2012-11-01
Michael Abc 2012-10-21
John    Abc 2012-10-23
John    HFD 2012-10-23
John    BHU 2012-11-09
Michael KSD 2012-11-08

我想要做的是在2012-11-012012-11-10之间计算个人服务。

以下是必需的输出

NAME    Abc Pqr Xyz
--------------------------------    
John    2   1   0
Michael 1   1   1
Denis   0   1   1
Sofy    1   0   0

这是我尝试过的:

SELECT  Name, COUNT(Distinct Service) 
FROM    [Appointment] 
WHERE   [DATE] between '2012-11-01 00:00:00.000' and '2012-11-10 23:59:59.999' 
AND     (Service = 'Abc' or Service = 'Pqr' or Service = 'Xyz') 
GROUP BY Name

提前谢谢。

1 个答案:

答案 0 :(得分:6)

SELECT Name,
       SUM(CASE WHEN Service = 'Abc' THEN 1 ELSE 0 END) Abc,
       SUM(CASE WHEN Service = 'Pqr' THEN 1 ELSE 0 END) Pqr,
       SUM(CASE WHEN Service = 'Xyz' THEN 1 ELSE 0 END) Xyz
FROM   TableName
WHERE [Date] BETWEEN CAST('2012-11-01' AS DATE) AND 
                     CAST('2012-11-10' AS DATE)
GROUP BY Name

SELECT Name, Abc, Pqr, Xyz
FROM 
  (
      SELECT [Name], [Service]
      FROM TableName
      WHERE [Date] BETWEEN CAST('2012-11-01' AS DATE) AND 
                           CAST('2012-11-10' AS DATE)
  ) p
  PIVOT
  (
      COUNT ([service])
      FOR [Service] IN ( [Abc], [Pqr], [Xyz] )
  ) AS s