MySQL Query select count in group by

时间:2014-05-27 04:21:13

标签: mysql sql

我有这些数据:

| bid_id | created             | auction_id | user_id | bid_credits | bid_credits_free | bid_rating | balance | bidded_price | last_for_user | bid_ip       | bid_type |
+--------+---------------------+------------+---------+-------------+------------------+------------+---------+--------------+---------------+--------------+----------+
|    735 | 2013-10-11 10:02:58 |       9438 |   62323 |           1 |                0 |     0.0000 |  100333 |         0.86 | Y             | 72.28.166.61 | single   |
|    734 | 2013-10-11 10:02:56 |       9438 |   76201 |           1 |                1 |     0.0000 |    1115 |         0.85 | Y             | 72.28.166.61 | single   |
|    733 | 2013-10-11 10:02:55 |       9438 |   62323 |           1 |                0 |     0.0000 |  100334 |         0.84 | N             | 72.28.166.61 | single   |
|    732 | 2013-10-11 10:02:54 |       9438 |   76201 |           1 |                1 |     0.0000 |    1116 |         0.83 | N             | 72.28.166.61 | single   |
|    731 | 2013-10-11 10:02:52 |       9438 |   62323 |           1 |                0 |     0.0000 |  100335 |         0.82 | N             | 72.28.166.61 | single   |

我试图获得" bid_credits"和" bid_credits_free"作为单独的价值......

所以查询应该返回我:

| user_id | count(bid_credits) | count(bid_credits_free) |
+---------+--------------------+-------------------------+
|   62323 |                  3 |                       0 |
|   76201 |                  2 |                       2 |

我使用的查询是:

select user_id, count(bid_credits), count(bid_credits_free) from bids_history 
where auction_id = 9438 and user_id in (62323,76201) group by user_id;

但它没有正确计算出价......有什么想法吗?

由于

4 个答案:

答案 0 :(得分:3)

在分组时使用总和而不是计数..应该有效

我也重新格式化,因此更容易阅读:)

SELECT 
    user_id, 
    SUM(bid_credits), 
    SUM(bid_credits_free) 
FROM bids_history 
WHERE auction_id = 9438 AND user_id IN (62323,76201) 
GROUP BY user_id;

你想要使用sum而不是count的原因是count只计算表中的行数,而不计算其中的whats的内容/值。所以当你按照这样的id进行分组时,你需要做一笔总和才能看到内容的实际添加内容。希望有助于解释一下事情:)

答案 1 :(得分:3)

你正在考虑使用它们,COUNT只计算行数。试试这个:

select user_id, sum(bid_credits), sum(bid_credits_free) from bids_history 
where auction_id = 9438 and user_id in (62323,76201) group by user_id;

答案 2 :(得分:1)

尝试此查询:

请使用SUM代替COUNT ...

SELECT user_id,SUM(bid_credits)AS bid_credits,SUM(bid_credits_free)AS bid_credits_free 来自bid_history WHERE auction_id = 9438 AND user_id IN(62323,76201) GROUP BY user_id;

答案 3 :(得分:0)

我认为这可能会对你有所帮助

select user_id, sum(bid_credits) AS bidCreditsCount, sum(bid_credits_free) AS bidCreditsFreeCount from bids_history 
where auction_id = 9438 and user_id in (62323,76201) group by user_id;