我正试图拉2个数字。一个是总共有多少医生(博士表)在1个月内有超过10个答案(答案表),总共75个答案,无论日期如何。另一个数字是相同的,但是在最近3个月内而不是1个月。
我使用下面的this answer回答来提出此查询:
SELECT D.name,
count(DISTINCT case when A.created > DATE_SUB(NOW(), INTERVAL 1 MONTH) then A.id end) as '1 month',
count(DISTINCT case when A.created > DATE_SUB(NOW(), INTERVAL 3 MONTH) then A.id end) as '1 quarter',
count(DISTINCT A.id) as total
FROM dr D
JOIN answer A ON A.dr_id=D.id AND A.status=3
GROUP BY D.id
这给了我需要的原始信息,但我不知道如何通过将它们与10和75答案要求进行比较来计算给出的计数。
答案 0 :(得分:0)
您可能需要稍微玩一下这个查询,但它应该可以为您提供所需的内容。基本上采用您的查询并将其用作派生表,并使用group by / having进一步汇总。
;with DrCounts as (
SELECT D.id,
count(DISTINCT case when A.created > DATE_SUB(NOW(), INTERVAL 1 MONTH) then A.id end) as '1month',
count(DISTINCT case when A.created > DATE_SUB(NOW(), INTERVAL 3 MONTH) then A.id end) as '1quarter',
count(DISTINCT A.id) as total
FROM dr D
JOIN answer A ON A.dr_id=D.id AND A.status=3
GROUP BY D.id)
select count(distinct D.id) as Dr1075
from DrCounts D
group by D.Id
having D.total >= 75 and D.1month >= 10
union
select count(distinct D.id) as Dr1075
from DrCounts D
group by D.Id
having D.total >= 75 and D.1quarter >= 10
答案 1 :(得分:0)
这样的事情,我想:
SELECT
COUNT(CASE WHEN total >= 75 AND `1month` > 10 THEN name END) AS `10+ per month count`,
COUNT(CASE WHEN total >= 75 AND `1quarter` > 10 THEN name END) AS `10+ per quarter count`
FROM (
SELECT D.name,
count(DISTINCT case when A.created > DATE_SUB(NOW(), INTERVAL 1 MONTH) then A.id end) as `1month`,
count(DISTINCT case when A.created > DATE_SUB(NOW(), INTERVAL 3 MONTH) then A.id end) as `1quarter`,
count(DISTINCT A.id) as total
FROM dr D
JOIN answer A ON A.dr_id=D.id AND A.status=3
GROUP BY D.id
) s