我有一个结果表,其中列出了一组值,每个值都链接到另一个包含结果日期的表。
我使用SQL来获取所有日期(使用CASE)但是我只能检索一系列结果。
Select
count(CASE
WHEN results.test_id IN ( SELECT id
FROM `test`
WHERE `posted`
BETWEEN '2011-07-01 00:00:00'
AND '2011-07-01 23:59:59')
THEN results.test_id
ELSE NULL
END) AS "1st July"
from `results`
WHERE results.window_id = 2 and results.mark > 90;
我还有另一个SQL查询,它获取所有范围,但一次只能用于一个日期。
SELECT
CASE
when mark > 90 then '>90%'
when mark > 80 then '>80%'
when mark > 70 then '>70%'
END as mark_results,
COUNT(*) AS count
FROM (SELECT mark from results where window_id =2) as derived
GROUP BY mark_results
ORDER BY mark_results;
我想要的是将所有内容放在统一查询中,显示每个结果范围的相关总计。如下:
Result Range | 1st July | 2nd July | 3rd July | 4th July
>90% | 0 | 0 | 0 | 1
>80% | 1 | 2 | 1 | 1
>70% | 4 | 5 | 5 | 4
以便每个范围的总数显示在其日期之下。
我认为这是可能的。
答案 0 :(得分:3)
以下语句在FROM子句中连接结果和测试。然后它按标记范围聚合查询,每天计数:
Select (CASE when mark > 90 then '>90%'
when mark > 80 then '>80%'
when mark > 70 then '>70%'
END) as mark_results,
sum(case when posted BETWEEN '2011-07-01 00:00:00' AND '2011-07-01 23:59:59' then 1 else 0 end) as July01,
sum(case when posted BETWEEN '2011-07-02 00:00:00' AND '2011-07-02 23:59:59' then 1 else 0 end) as July02,
. . .
from `results` r join
test t
on r.test_id = t.test_id
WHERE r.window_id = 2 and results.mark > 90
group by (CASE when mark > 90 then '>90%'
when mark > 80 then '>80%'
when mark > 70 then '>70%'
END)
order by 1
只需将所需日期添加到SELECT子句中即可。
我应该补充一下。 。 。如果你想要所有的日期,你需要将它们放在不同的行上:
Select date(posted) as PostedDate,
(CASE when mark > 90 then '>90%'
when mark > 80 then '>80%'
when mark > 70 then '>70%'
END) as mark_results,
count(*) as cnt
. . .
from `results` r join
test t
on r.test_id = t.test_id
WHERE r.window_id = 2 and results.mark > 90
group by date(posted),
(CASE when mark > 90 then '>90%'
when mark > 80 then '>80%'
when mark > 70 then '>70%'
END)
order by 1, 2
实际上,您可能会考虑为每个日期设置一个单独的行,并将范围作为列进行旋转。