1

私は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-01との間に個人向けのサービスを数えることです2012-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

前もって感謝します。

4

1 に答える 1

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
于 2012-11-10T11:26:35.327 に答える