有条件分组

时间:2018-11-12 13:01:04

标签: php mysql

我必须在php中显示一些数据,数据结构是这样的

id  channel_id  added_by

1     1          9999
2     1          195
3     8          9999
4     1          180
5     1          195
6     8          9999
7     1          9999
8     1          195
9     8          9999

我只需要这样显示频道ID = 1的总数

channel_id   total  added_by

1            2           9999
1            4          -1

就像所有通道ID的计数加9999,所有其他通道的计数都假定为(-1)

我能够做到

SELECT channel_id, added_by, sum(id) as total 
from table 
where channel_id = 1 
group by channel_id  ,added_by;

但是它给出了以下结果,这不是我所需要的

channel_id  added_by total 
1            9999      2
1             195      3
1             180      1

请帮助或给出任何帮助的提示

4 个答案:

答案 0 :(得分:2)

使用CASE..WHEN表达式,您可以确定一个“修改后的” added_by值,而在修改后的值上确定GROUP BY

此外,SUM(id)不会为您提供正确的行数。宁愿将id值加起来。您可以使用COUNT(*)来计算行数:

SELECT channel_id, 
       CASE 
         WHEN added_by <> 9999 THEN -1 
         ELSE 9999 
       END AS modified_added_by, 
       COUNT(*) as total 
FROM your_table_name 
WHERE channel_id = 1 
GROUP BY channel_id, modified_added_by

结果

| channel_id | modified_added_by | total |
| ---------- | ----------------- | ----- |
| 1          | -1                | 4     |
| 1          | 9999              | 2     |

View on DB Fiddle

答案 1 :(得分:1)

希望这会对您有所帮助。

SELECT count(*) as total, channel_id, added_by from table group by channel_id, added_by;

答案 2 :(得分:1)

http://sqlfiddle.com/#!9/437406/2

SELECT channel_id,
       IF(added_by=9999,9999,-1) new_col,
       COUNT(*)
FROM `table`
GROUP BY channel_id, new_col

答案 3 :(得分:0)

您可以尝试以下方法:

SELECT channel_id,
if(9999,9999,-1) as added_by,
sum(id) as total
from table
where channel_id = 1
group by channel_id,added_by;