ソースコード
SELECT 
    AGE_GRP.AGE_NAME AS 年齢階層,
    -- CASE句を用いて時間コードの値で場合分けし、対象人数を対応するカラムに振分けます
    -- 最後に、年齢コードでグルーピングを行い、振分けた値をサマリして表示します
    -- AS句で変更している表示項目名の先頭が数字なので、ダブルクォーテーションで項目名を囲っています
    SUM(CASE WHEN TIME_CODE = 120 THEN TARGET_POP ELSE 0 END) AS "5時間未満",
    SUM(CASE WHEN TIME_CODE = 130 THEN TARGET_POP ELSE 0 END) AS "5時間以上6時間未満",
    SUM(CASE WHEN TIME_CODE = 140 THEN TARGET_POP ELSE 0 END) AS "6時間以上7時間未満",
    SUM(CASE WHEN TIME_CODE = 150 THEN TARGET_POP ELSE 0 END) AS "7時間以上8時間未満",
    SUM(CASE WHEN TIME_CODE = 160 THEN TARGET_POP ELSE 0 END) AS "8時間以上9時間未満",
    SUM(CASE WHEN TIME_CODE = 170 THEN TARGET_POP ELSE 0 END) AS "9時間以上",
    SUM(CASE WHEN TIME_CODE = 180 THEN TARGET_POP ELSE 0 END) AS 不詳
FROM SLEEP_TIME_DTL
INNER JOIN AGE_GRP ON AGE_GRP.AGE_CODE = SLEEP_TIME_DTL.AGE_CODE
GROUP BY AGE_GRP.AGE_CODE
ORDER BY AGE_GRP.AGE_CODE;

----------------------------------------------------------------------------------------------------------
SELECT 
    AGE_GRP.AGE_NAME AS 年齢階層,
    (CASE WHEN TIME_CODE = 120 THEN TARGET_POP ELSE 0 END) AS "5時間未満",
    (CASE WHEN TIME_CODE = 130 THEN TARGET_POP ELSE 0 END) AS "5時間以上6時間未満",
    (CASE WHEN TIME_CODE = 140 THEN TARGET_POP ELSE 0 END) AS "6時間以上7時間未満",
    (CASE WHEN TIME_CODE = 150 THEN TARGET_POP ELSE 0 END) AS "7時間以上8時間未満",
    (CASE WHEN TIME_CODE = 160 THEN TARGET_POP ELSE 0 END) AS "8時間以上9時間未満",
    (CASE WHEN TIME_CODE = 170 THEN TARGET_POP ELSE 0 END) AS "9時間以上",
    (CASE WHEN TIME_CODE = 180 THEN TARGET_POP ELSE 0 END) AS 不詳
FROM SLEEP_TIME_DTL
INNER JOIN AGE_GRP ON AGE_GRP.AGE_CODE = SLEEP_TIME_DTL.AGE_CODE
--GROUP BY AGE_GRP.AGE_CODE
ORDER BY AGE_GRP.AGE_CODE;

----------------------------------------------------------------------------------------------------------

WITH K AS ( 
    SELECT
        TIME_CODE AS T
        , AGE_CODE AS A
        , SUM(TARGET_POP) AS P 
    FROM
        SLEEP_TIME_DTL 
    GROUP BY
        TIME_CODE
        , AGE_CODE
) 
SELECT
    AGE_GRP.AGE_NAME AS "年齢階層"
    , K_120.P AS "5時間未満"
    , K_130.P AS "5時間以上6時間未満"
    , K_140.P AS "6時間以上7時間未満"
    , K_150.P AS "7時間以上8時間未満"
    , K_160.P AS "8時間以上9時間未満"
    , K_170.P AS "9時間以上"
    , K_180.P AS "不詳" 
FROM
    AGE_GRP 
    INNER JOIN K AS K_120 ON AGE_GRP.AGE_CODE = K_120.A AND K_120.T = 120 
    INNER JOIN K AS K_130 ON AGE_GRP.AGE_CODE = K_130.A AND K_130.T = 130 
    INNER JOIN K AS K_140 ON AGE_GRP.AGE_CODE = K_140.A AND K_140.T = 140 
    INNER JOIN K AS K_150 ON AGE_GRP.AGE_CODE = K_150.A AND K_150.T = 150 
    INNER JOIN K AS K_160 ON AGE_GRP.AGE_CODE = K_160.A AND K_160.T = 160 
    INNER JOIN K AS K_170 ON AGE_GRP.AGE_CODE = K_170.A AND K_170.T = 170 
    INNER JOIN K AS K_180 ON AGE_GRP.AGE_CODE = K_180.A AND K_180.T = 180
ORDER BY AGE_GRP.AGE_CODE;
提出情報
提出日時2022/11/11 12:09:41
コンテスト練習用コンテスト
問題年齢別睡眠時間分析
受験者sqlbcamp
状態 (詳細)AC
(Accepted: 正答)
メモリ使用量80 MB
メッセージ
テストケース(通過数/総数)
2/2
状態
メモリ使用量
データパターン1
AC
80 MB
データパターン2
AC
80 MB