SQL“group by”只返回第一行 - bis

时间:2015-09-22 13:53:47

标签: mysql sql group-by

我从中理解:SQL group by returns just first row 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

如何?

1 个答案:

答案 0 :(得分:1)

您不能使用group_ID代替0,因为它是INT字段。您可以使用例如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;

String annualInterestRate1;
Double.parseDouble(annualInterestRate1);
JOptionPane.showInputDialog("Enter your 1st annual interest rate");

SQLFiddle demo