2012-11-10 89 views
1

我對SQL相當陌生,而且卡在查詢中。我有以下的表稱爲Appointment按照名稱計算唯一服務和組的SQL查詢

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 

預先感謝您。

+2

你可以發佈你已經嘗試查詢?這將有助於解釋你出錯的地方。 – Ren

+0

@Ren:從[預約] ['DATE]到'2012-11-01 00:00:00.000'和'2012-11-10 23:59:59.999' 之間選擇姓名,計數(區別服務) 和(Service ='Abc'或Service ='Pqr'或Service ='Xyz') group by Name –

+1

@KaustubhLohiya:下一次編輯您的問題而不是評論它。順便說一句,你還應該標記rdbms(f.e。MySql)。 –

回答

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 
+1

嘿,非常感謝。完美的工作 –

+0

不客氣! –