自聯接以比較同一張表中的季度數據? (Self join to compare quarterly data from same table?)


問題描述

自聯接以比較同一張表中的季度數據? (Self join to compare quarterly data from same table?)

I'm helping a small rural health system add some databanking to their operations. They currently keep track of some operational statistics that they report each quarter.

I'd like to put the meat of these responses in one table and do historical comparisons from it. I'll have some additional tables for normalization, but here's the main one.

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

The output I'm looking for is to put those quarterly responses for each question side-by-side so I can calculate changes better and easy up my PHP processing. Below is the desired output:

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

I'm new to SQL (using MySQL 5) and the only thing I can think of is I need a self join. I've tried but can't seem to get it. Am I approaching the table structure the correct way for this kind of historical analysis?

Any pointers would be a big help and a help to our project!

Thanks!


參考解法

方法 1:

You could group by question, and then use a combination of case and max to select the answer for that quarter.

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

In this example the max doesn't actually max anything, it ends up selecting the only quarter for which the case returns a value.

方法 2:

Well assuming you want to get that output for a specific year, eg. 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

(by epitomeAndomarreko_t)

參考文件

  1. Self join to compare quarterly data from same table? (CC BY-SA 3.0/4.0)

#SQL #MySQL #join






相關問題

如何組合表和視圖? (How do combine tables and views?)

Sql中的WHERE,結合兩個快速條件會成倍增加成本 (WHERE in Sql, combining two fast conditions multiplies costs many times)

Oracle : Выкарыстанне ўкладзенага запыту супраць выкарыстання адлюстравання (Oracle : Using nested query vs using mapping)

SQL在友誼表中插入值基於 (SQL insert value in friendship table based on)

SQL 查詢沒有返回任何值 (SQL query did not return any values)

PL/SQL 塊和循環練習 (PL/SQL block and LOOP exercise)

查找與日曆相比缺失的日期 (Find missing date as compare to calendar)

在 C# 中使用數據庫需要一些幫助 (Need some help working with databases in C#)

如何設計n多對多關係以使sql查詢更容易 (How to design n many to many relationship in order make sql query easily)

在 SQL 中從 3 個視圖創建一個視圖 (Creating a view from 3 views in SQL)

java while (resultset.next()) 不返回同一列中的所有數據 (java while (resultset.next()) does not return all data in the same column)

從訪問表單的文本字段傳遞開始和結束日期參數 (Pass start and end date parameter from text field of access form)







留言討論