将“名称”列中具有相同值的所有行合并为一行

时间:2019-08-02 16:15:11

标签: sql

我从月度数据集中获取了大量交易的详细信息,其中一些交易存在于每个数据集中,而有些则不在每个数据集中,然后将它们组合成一个数据集,称为“月度月度数据集”。我想将每个月的“阶段”值存储在新列(例如,2月阶段)下,如果该月没有任何值,请将其设置为“不适用”。

我遇到的关键问题是,我不知道如何将所有具有相同名称的交易合并到一个列中,因此,每次交易显示时,我的当前代码都有一行,除了不适用说,这是本月的一个,对我没有太大帮助。

我是SQL的新手,所以我确定我缺少一些简单的东西

SELECT
         "Deal Name",
         if("month"  = 'February', "Stage", 'None') AS "Stage February",
         if("month"  = 'March', "Stage", 'None') AS "Stage March",
         if("month"  = 'April', "Stage", 'None') AS "Stage April",
         if("month"  = 'May', "Stage", 'None') AS "Stage May",
         if("month"  = 'June', "Stage", 'None') AS "Stage June",
         if("month"  = 'July', "Stage", 'None') AS "Stage July"
FROM  "Month by Month Stage Data"

1 个答案:

答案 0 :(得分:0)

我猜你想要:

SELECT "Deal Name",
        max(case when "month"  = 'February' then "Stage" end) AS "Stage February",
        max(case when "month"  = 'March' then "Stage" end) AS "Stage March",
        max(case when "month"  = 'April' then "Stage" end) AS "Stage April",
        max(case when "month"  = 'May' then "Stage" end) AS "Stage May",
        max(case when "month"  = 'June' then "Stage" end) AS "Stage June",
        max(case when "month"  = 'July' then "Stage" end) AS "Stage July"
FROM "Month by Month Stage Data"
GROUP BY "Deal Name";

以上返回NULL而不是'None'。如果您确实想要'None',请使用COALESCE()

SELECT "Deal Name",
        coalesce(max(case when "month"  = 'February' then "Stage" end), 'None') AS "Stage February",
        coalesce(max(case when "month"  = 'March' then "Stage" end), 'None') AS "Stage March",
        coalesce(max(case when "month"  = 'April' then "Stage" end), 'None') AS "Stage April",
        coalesce(max(case when "month"  = 'May' then "Stage" end), 'None') AS "Stage May",
        coalesce(max(case when "month"  = 'June' then "Stage" end), 'None') AS "Stage June",
        coalesce(max(case when "month"  = 'July' then "Stage" end), 'None') AS "Stage July"
FROM "Month by Month Stage Data"
GROUP BY "Deal Name";
相关问题