0

我有一个结果表,其中列出了一组值,每个值都链接到另一个表,其中包含生成结果的日期。

我有工作 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

以便每个范围的总数显示在其日期下方。

我认为这是可能的。

4

1 回答 1

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

事实上,您可能会考虑为每个日期设置一个单独的行,并将范围作为列进行透视。

于 2012-07-27T21:19:30.760 回答