【问题标题】:How to use group by with Self join如何通过自我加入使用 group by
【发布时间】:2020-12-05 09:08:45
【问题描述】:

我有这样的桌子

  • 累计、金额、x、姓名、时间
  • 1, 100, dep, bbb, 10
  • 1, 200, dep, bbb, 10
  • 1, 80, 机智, bbb, 10
  • 1, 90, 机智, bbb, 10
  • 2, 100, dep, bbb, 20
  • 2, 101, 机智, bbb, 20
  • 1, 100, dep, ccc, 10
  • 1、150、机智、ccc、10

从这里我想显示一个表格

  • 姓名、累积、时间、dep_amt、wid_amt、利润
  • bbb, 1, 10, 300, 170, 130
  • bbb, 2, 20, 100, 101, -1
  • ccc, 1, 10, 100, 150, -50

所以,我尝试了自我加入

SELECT a.Name, a.Acc, a.Time, a.Amount as dep_amt, new.Amount as wid_amt, (a.Amount-new.Amount) as profit
FROM all_data as a, all_data as new
where a.Time = new.Time
and a.name = new.name
and a.acc =new.acc
and a.x= "dep”
and new.x="wit"

但是,我不能对它使用 Group by(error contains nonaggregated column),并且这个 sql 会导致一个包含很多行的表。怎么办???

【问题讨论】:

  • 如果您按某些内容进行分组,则必须汇总结果。你还没有展示你想如何将它分组,所以不可能给出建议。但想法是这样的:例如,如果您按名称分组,那么应该为该名称指定什么时间?还是金额?

标签: sql


【解决方案1】:

这看起来像条件​​聚合,而不是自联接:

select Name, Acc, Time,
       sum(case when x = 'dep' then amount else 0 end) as dep_amt,
       sum(case when x = 'wit' then amount else 0 end) as wit_amt,
       sum(case when x = 'dep' then amount 
                when x = 'wit' then - amount
                else 0
           end) as profit
from t
group by Name, Acc, Time;

Here 是一个 dbfiddle。

自联接不起作用,因为每个组中有多个“dep”和“wit”行。在每个组中,您会得到这些行的笛卡尔积,从而导致总计算错误。

【讨论】:

    【解决方案2】:

    好像你想要条件聚合。

    SELECT name,
           acc,
           time,
           sum(CASE
                 WHEN x = 'dep' THEN
                   amount
                 ELSE
                   0
               END) dep_amt,
           sum(CASE
                 WHEN x = 'wit' THEN
                   amount
                 ELSE
                   0
               END) dep_wit,
           sum(CASE
                 WHEN x = 'dep' THEN
                   amount
                 ELSE
                   0
               END)
           -
           sum(CASE
                 WHEN x = 'wit' THEN
                   amount
                 ELSE
                   0
               END) profit
           FROM all_data
           GROUP BY name,
                    acc,
                    time;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      相关资源
      最近更新 更多