根据mysql中使用GROUP BY的列选择特定行

时间:2013-09-18 08:07:48

标签: mysql sql select count distinct

这是我桌子的记录:

item_code   |   qty

001             1
001             1
002             2    
002             2  
003             2
004             1
005             3

这是我根据item_code GROUP BY选择不同qty和qty总数的代码:

select item_code, sum(qty) as qty
from imp_inv
group by item_code

这就是结果:

item_code   |   qty

001             2
002             4    
003             2
004             1
005             3

我正在努力的是,如何选择item_code qty的where子句,这就是我尝试的内容:

select item_code, sum(qty) as qty
from imp_inv where qty = 2
group by item_code

这就是结果:

item_code   |   qty

002             2    
002             2  
003             2

上面的代码只选择item_code为2的qty,我希望根据item_code的总数来选择qty ,这是我想要的结果:

item_code   |   qty

001             2  
003             2

希望大家都明白我的问题,谢谢你的帮助。

更新

我删除了所有选择查询中的不同内容。

我将item_code的数量更改为3。

我将COUNT更改为SUM。

3 个答案:

答案 0 :(得分:4)

请尝试以下:

 HAVING count(qty) = 2

答案 1 :(得分:2)

试一试:

select q.item_code, q.qty from 
(select item_code as item_code, count(qty) as qty from imp_inv group by item_code) as q
where q.qty=2

答案 2 :(得分:2)

您不应该将列重命名为已经作为列名存在的别名,这会让您感到困惑。

WHERE qty = 2 是指 QTY,当您将其更改为 HAVING qty = 2 时,它会引用别名< strong> count(qty)as qty 。

只需使用HAVING和其他名称,例如 count(qty)作为cnt

顺便说一句,您不需要DISTINCT,因为它始终适用于所有列,GROUP BY altready返回一个不同的值列表。

相关问题