2016-06-13 80 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条款。