自联接比较来自同一表的季度数据?

时间:2010-12-28 12:32:55

标签: sql mysql join

我正在帮助一个小型农村卫生系统为其运营添加一些数据库。他们目前跟踪他们每个季度报告的一些运营统计数据。

我想把这些回答的内容放在一张桌子上,并从中进行历史比较。我将有一些额外的表用于规范化,但这是主要的。

+-------+----------+-------------+----------+
| year  | quarter  | question_id | response |
+-------+----------+-------------+----------+
| 2000  | 1        | 100         | 50       |
+-------+----------+-------------+----------+
| 2000  | 2        | 100         | 100      |
+-------+----------+-------------+----------+
| 2000  | 1        | 200         | 75       |
+-------+----------+-------------+----------+
| 2000  | 2        | 200         | 25       |
+-------+----------+-------------+----------+

我正在寻找的输出是将每个问题的季度响应并排放置,这样我就可以更好地计算更改并轻松完成PHP处理。以下是所需的输出:

+-------------+----------------------+----------------------+
| question_id | 1st quarter response | 2nd quarter response |
+-------------+----------------------+----------------------+
| 100         | 50                   | 100                  |
+-------------+----------------------+----------------------+
| 200         | 75                   | 25                   |
+-------------+----------------------+----------------------+

我是SQL的新手(使用MySQL 5),我唯一能想到的就是我需要一个自我加入。我试过但似乎无法得到它。我是否正在接近表结构进行这种历史分析的正确方法?

任何指针对我们的项目都有很大的帮助和帮助!

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以group by提问,然后使用casemax的组合来选择该季度的答案。

select  question_id
,       max(case when quarter = 1 then question_responses end) as Q1
,       max(case when quarter = 2 then question_responses end) as Q2
,       max(case when quarter = 3 then question_responses end) as Q3
,       max(case when quarter = 4 then question_responses end) as Q4
from    question_responses
where   year = 2000
group by
        question_id

在此示例中,max实际上并不max任何内容,最终会选择case返回值的唯一季度。

答案 1 :(得分:0)

假设您希望获得特定年份的输出,例如。 2000:

SELECT
    question_id,
    (SELECT response FROM question_responses WHERE year = qr.year AND question_id = qr.question_id AND quarter = 1) AS qrt_resp_1,
    (SELECT response FROM question_responses WHERE year = qr.year AND question_id = qr.question_id AND quarter = 2) AS qrt_resp_2
    FROM question_responses AS qr
    WHERE year = 2000
    GROUP BY question_id