9

我正在努力解决这个问题。我有一张这样的桌子。

    +-------------+-------+
    | type        | COUNT |
    +-------------+-------+
    | A           |     1 |
    | C           |     5 |
    | B           |     4 |
    +-------------+-------+

我要查询表,结果一定是这样的。

+-------------+-------+
| type        | COUNT |
+-------------+-------+
| A           |     1 |
| B           |     5 |
| C           |     9 |
| D           |     0 |
+-------------+-------+

询问:

select type , COUNT from TABLE order by FIELD(type,'A','B','C','D') ; 

如果该列type具有 'A,B,C,D' 的值,则它工作正常。在某些情况下,FIELD('A','B','C','D')某些列的顺序在 table 中可能没有值。在这种情况下,我想为它输入 0 并构造一个 result 。

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
4

1 回答 1

13

怎么样:

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') ; 


SQL小提琴演示

于 2012-11-16T12:08:51.093 回答