2016-06-13 76 views
0

以下計算值是我的表架構: - 約會SQL:基於兩種不同的條件

-------------------------------------- 
| schID | appointment_date | amount | location | 
-------------------------------------- 

我想火一個查詢在那裏我能得到今年量,總appointment_date的總和,即2016年其餘appointment_date今年即2016年

所以我寫了下面的查詢來計算上述領域: -

SELECT sum(a.amount) as total, 
     count(distinct a.appointment_date) as total_appointment, 
     count(distinct a2.appointment_date) as remaining appointments 
from Appointments a 
LEFT JOIN Appointments a2 ON a.schID = a2.schID 
WHERE a2.appointment_date > GETDATE() AND year(a.appointment_date) = 2016 
group by a.location 

上面的查詢犯規返回值按要求:(

該數據庫屬於SQL Server。

回答

2

您可以使用條件聚集此:

SELECT sum(amount) as total, 
     count(appointment_date) as total_appointment, 
     count(DISTINCT CASE 
       WHEN appointment_date > GETDATE() AND YEAR(appointment_date) = 2016 
        THEN DATE(appointment_date) 
      END) as remaining appointments 
from Appointments a 
group by a.location 
+0

感謝您的快速回復,但我們怎麼能包括這樣,只有唯一的日期被計算的情況下,部分「不同」。 – Villie

+0

感謝它的工作! – Villie

+0

@Villie你還在'THEN'之後加了'DATE(appointment_date)'嗎? 'DATE'函數只在'appointment_date'不是'DATE'類型時才需要。 –

1

你不應該需要一個join對於這種類型的查詢:

SELECT sum(a.amount) as total, count(a.appointment_date) as total_appointment, 
     sum(case when a.appointment_date > getdate() then 1 else 0 
      end) as remaining appointments 
from Appointments a 
where year(a.appointment_date) = year(GETDATE()); 

如果你需要的位置擊穿,則包括location同時在selectgroup by條款。