以下是我的表架构: - 约会
--------------------------------------
| schID | appointment_date | amount | location |
--------------------------------------
我想点击一个查询,我可以获得金额总额,今年总预约数,即2016年和今年剩余的预约日期,即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。
答案 0 :(得分: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
答案 1 :(得分: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
和select
条款中加入group by
。