简体   繁体   English

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

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

I understand from this: SQL group by returns just first row that MySQL returns only the first value found for a group. 我从中了解到: SQL group by仅返回第一行 ,而MySQL仅返回为组找到的第一个值。

To simplify I have the following tables: 为了简化,我有下表:

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

Last table is an associative table many-to-many between products and groups. 最后一个表是产品和组之间多对多的关联表。

I want to group by the products, summing up their quantity ( qty ), and when all the products summed are in a single group, I want the group name selected, otherwise I want "??" 我想按产品分组,求和它们的数量( qty ),当所有求和的产品归为一个组时,我要选择组名,否则我要“ ??” returned. 回来。

MySQL always returns the first group it finds: 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;

I get: 我得到:

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

Edit: maybe my question was not clear. 编辑:也许我的问题不清楚。 Instead of what I get, I want: 我想要得到的不是我得到的,而是:

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

How? 怎么样?

You can't use ??? 您不能使用??? instead of group_ID since it's an INT field. 而不是group_ID因为它是一个INT字段。 You can use for example 0 . 您可以使用例如0 Try to use CASE : 尝试使用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 demo SQLFiddle演示

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

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