我正在努力解决这个问题。我有一张这样的桌子。
+-------------+-------+
| type | COUNT |
+-------------+-------+
| A | 1 |
| C | 5 |
| B | 4 |
+-------------+-------+
我想查询表格,结果必须是这样的。
+-------------+-------+
| type | COUNT |
+-------------+-------+
| A | 1 |
| B | 5 |
| C | 9 |
| D | 0 |
+-------------+-------+
QUERY:
select type , COUNT from TABLE order by FIELD(type,'A','B','C','D') ;
如果列type
具有'A,B,C,D'的值,则它可以正常工作。在某些情况下,FIELD('A','B','C','D')
某些列的顺序在表格中可能没有值。在这种情况下,我想为它设置0并构造一个结果。
D表中没有。所以把'0'换成它。
显示创建表输出
CREATE TABLE `Summary` (
`TIMESTAMP` bigint(20) NOT NULL DEFAULT '0',
`type` varchar(50) NOT NULL DEFAULT '',
`COUNT` bigint(19) NOT NULL,
PRIMARY KEY (`TIMESTAMP`,`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
答案 0 :(得分:8)
这是怎么回事:
select a.col as type,coalesce (`COUNT`,0) as `count`
from
(select 'A' as col union all
select 'B' as col union all
select 'C' as col union all
select 'D' as col )a
left join Table1 T
on a.col=T.type
order by FIELD(a.col,'A','B','C','D') ;