繁体   English   中英

SQL“分组依据”仅返回第一行-bis

[英]SQL “group by” returns just first row - bis

我从中了解到: SQL group by仅返回第一行 ,而MySQL仅返回为组找到的第一个值。

为了简化,我有下表:

Products
----------------
id | description
----------------
1  | Product-1
2  | Product-2
3  | Product-3


Groups
------
id | description
----------------
1  | Group-1
2  | Group-2


nxm_Products_Groups
---------------------
product_id | group_id | qty
---------------------
1          |   1      | 10
1          |   2      | 10
2          |   1      | 10
3          |   1      | 10

最后一个表是产品和组之间多对多的关联表。

我想按产品分组,求和它们的数量( qty ),当所有求和的产品归为一个组时,我要选择组名,否则我要“ ??” 回来。

MySQL总是返回找到的第一个组:

SELECT  
    G.id AS GROUP_ID,
    G.description,  
    P.id AS PRODUCT_ID,  
    P.description,  
    SUM(GP.qty) AS QTY 
 FROM  
    Groups G  
 JOIN nxm_Products_Groups GP ON (G.id = GP.group_id)  
 JOIN Products P ON (P.id = GP.product_id)  
 GROUP BY P.id  
 ORDER BY GP.group_id;

我得到:

GROUP_ID|description|PRODUCT_ID|description|QTY
1       |Group 1    |2         |Product-2  |10
1       |Group 1    |3         |Product-3  |10
1       |Group 1    |1         |Product-1  |20

编辑:也许我的问题不清楚。 我想要得到的不是我得到的,而是:

GROUP_ID|description|PRODUCT_ID|description|QTY
1       |Group 1    |2         |Product-2  |10
1       |Group 1    |3         |Product-3  |10
???     |???        |1         |Product-1  |20

怎么样?

您不能使用??? 而不是group_ID因为它是一个INT字段。 您可以使用例如0 尝试使用CASE

SELECT  
    CASE WHEN COUNT(*)=1 THEN G.id ELSE 0 END AS GROUP_ID,
    CASE WHEN COUNT(*)=1 THEN G.description ELSE '\?\?' END AS GROUP_DESC,  
    P.id AS PRODUCT_ID,  
    P.description,  
    SUM(GP.qty) AS QTY 
 FROM  
    Groups G  
 JOIN nxm_Products_Groups GP ON (G.id = GP.group_id)  
 JOIN Products P ON (P.id = GP.product_id)  
 GROUP BY P.id  
 ORDER BY GROUP_ID;

SQLFiddle演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM