Open1

sql contest 1 (topsic)

mk83mk83

4

test case 1が通らないやつ。prefectureを結合すれば通る。なぜ。

SELECT
    p.pf_code as "都道府県コード",
    p.pf_name as "都道府県名",
    MAX(CASE tmp.ranking WHEN 1 THEN tmp.nation_name END) AS "1位 国名",
    MAX(CASE tmp.ranking WHEN 1 THEN tmp.amt END) AS "1位 人数",
    MAX(CASE tmp.ranking WHEN 2 THEN tmp.nation_name END) AS "2位 国名",
    MAX(CASE tmp.ranking WHEN 2 THEN tmp.amt END) AS "2位 人数",
    MAX(CASE tmp.ranking WHEN 3 THEN tmp.nation_name END) AS "3位 国名",
    MAX(CASE tmp.ranking WHEN 3 THEN tmp.amt END) AS "3位 人数",
    SUM(tmp.amt) AS "合計人数"
FROM prefecture p
JOIN (  
    SELECT
        f.pf_code,
        p.pf_name,
        RANK() OVER(
            PARTITION BY
                f.pf_code
            ORDER BY 
                f.amt DESC,
                f.pf_code
        ) AS ranking,
        n.nation_name,
        f.amt
    FROM foreigner f
    JOIN nationality n
    ON f.nation_code=n.nation_code
    JOIN prefecture p
    ON f.pf_code=p.pf_code
    WHERE f.nation_code <> "113"
) tmp
ON p.pf_code=tmp.pf_code
GROUP BY tmp.pf_code
ORDER BY "合計人数" DESC, p.pf_code;