我如何实现此mysql组查询

时间:2018-10-31 12:35:52

标签: mysql group-by

我有两个表A和B。 我的目标是列出A中的每一行,同时附加B中的“金额”总和。

像这样:

SELECT a.name, 
       SUM(b.amount) as amount 
FROM a 
LEFT JOIN b ON a.id = b.a_id 
GROUP BY a.id 

在此之前没有问题,但是我还需要检查B表的'shop_id'是否匹配值,如果匹配,我希望该单行的'金额',而不是所有分组行的SUM。我希望这是可以理解的。

Table A  
id     name
----------------
1      john
2      doe
3      smith

Table B
a_id    amount    shop
-----------------------
1         4        1
1         3        2
2         2        2
2         7        3
3         3        3
3         1        2

期望的结果与'shop'= 1:

name   amount    shop
---------------------
john     4         1         //no SUM, only the value of amount where shop=1
doe      9         0         //sum(7,2) because shop is not 1
smith    4         0         //sum(3,1) 

我在想SUM()选择处的if语句与此类似,但是下面的语句未返回所需的分组行值

SELECT a.name,
       ( CASE
           WHEN b.shop <> 1 THEN Sum(b.amount)
           ELSE b.amount
         end ) AS amount,
       ( CASE
           WHEN b.shop <> 1 THEN 0
           ELSE b.shop
         end ) AS shop
FROM   a
       LEFT JOIN b
              ON a.id = b.a_id
GROUP  BY a.id  

有什么想法吗?有没有办法将这种条件放在GROUP上,例如:case shop<>1 THEN .... ELSE GROUP BY a.id ??

2 个答案:

答案 0 :(得分:2)

您使用正确的条件聚合是正确的。这是应该工作的版本:

SELECT
    a.name,
    CASE WHEN MAX(CASE WHEN b.shop = 1 THEN 1 ELSE 0 END) > 0
         THEN SUM(CASE WHEN b.shop = 1 THEN b.amount ELSE 0 END)
         ELSE SUM(b.amount) END AS amount,
    MAX(CASE WHEN b.shop = 1 THEN 1 ELSE 0 END) AS shop
FROM a
LEFT JOIN b
    ON a.id = b.a_id
GROUP BY
    a.name;

enter image description here

Demo

答案 1 :(得分:2)

  • 您将需要Left Join与表b两次。
  • 首次加入将启用求和。
  • 仅当shop = 1时,第二次联接才会联接。因此,如果由于第二次联接而获得一些非空值,我们会考虑,否则求和

尝试以下操作:

SELECT 
  a.id, 
  a.name, 
  COALESCE(MAX(b2.amount), SUM(b1.amount)) AS amount, 
  COALESCE(b2.shop, 0) AS shop 
FROM a 
LEFT JOIN b AS b1 ON a.id = b1.a_id 
LEFT JOIN b AS b2 ON a.id = b2.a_id AND b2.shop = 1
GROUP BY a.id, a.name 

结果

| id  | name  | amount | shop |
| --- | ----- | ------ | ---- |
| 1   | john  | 4      | 1    |
| 2   | doe   | 9      | 0    |
| 3   | smith | 4      | 0    |

View on DB Fiddle