【问题标题】:sql grouping of calculationsql分组计算
【发布时间】:2020-01-22 22:59:11
【问题描述】:

有没有人有解决方案如何用案例陈述对两个类别的总和进行分组?

在下面的屏幕截图中,我想将两行合并为一,只在 flag1total 和 flag2total 列中显示 PE 和 NPE 总和,但它不起作用。

这是我目前的 SQL:

select type, flag, coalesce(sum(value),0) total,
case when flag = "NPE" then coalesce(sum(value),0) else "" end as flag1total,
case when flag = "PE" then coalesce(sum(value),0) else "" end as flag2total
from maintable
group by type, flag;

数据是这样的

 type     flag          value
 P_OTH    PE            23525
 P_OTH    PE            13525
 P_CRE    PE            232525
 P_OTH    PE            4525
 ....

预期的结果是这样的(每种类型一行和标志的矢量化总和):

 type     flag          total      flag1total   flag2total
 P_OTH    PE, NPE       3023624    1132707      1890917

【问题讨论】:

  • 更新您的问题并将预期结果(和数据样本)添加为表格文本..(不是图像)
  • 对不起,我不清楚。您想要 PE 的总和、NPE 的总和以及 NPE 和 PE 的总和?
  • 更新了问题...我只想要 flag1total 和 flag2total...一般总和只是为了说明
  • 我想你会在那里找到幸福:stackoverflow.com/questions/17664436/…

标签: mysql sql group-by case


【解决方案1】:

您需要在 sum 函数中使用 case。试试这样的:

select type, coalesce(sum(value),0) total,
    coalesce(sum(case when flag = "NPE" then value else 0 end),0)   as flag1total,
    coalesce(sum(case when flag = "PE" then value else 0 end),0)  as flag2total
 from maintable
 group by type;

注意,'flag' 不能在 group by 子句中。

【讨论】:

  • 只是为了确定,这只适用于分组时,否则我可以在我的函数之外使用我的旧查询?
  • @GabrielCandido 。 . . coalesce() 是不必要的。
  • @dfhdfh 是的,在外面用也没有错,看你希望结果如何。
  • @GordonLinoff 是的,没有考虑清楚。感谢您的指出。
【解决方案2】:

下面你需要吗-

SELECT  type
       ,GROUP_CONCAT(flag, ', ') flag
       ,coalesce(sum(value),0) total
       ,coalesce(sum(case when flag = "NPE" then value else 0 end),0)   as flag1total
       ,coalesce(sum(case when flag = "PE" then value else 0 end),0)  as flag2total
 from maintable
 group by type;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2021-12-18
    相关资源
    最近更新 更多