0

我有一个简单的表,它有一列id。此列不是主键(PK)。id 的值可以在 1 到 10 之间。我想编写一个查询,为我提供单个表中所有数字的计数,如下所示:

one   two three four ............
 5     8    9     15 ...........

我知道我可以编写这样的查询select count(*) from table where id = 1。但这返回给我单个数字计数的意思id =1。我需要在单个查询中编写 1 到 10 之间的所有数字的查询。

4

2 回答 2

1

带旋转

类似于以下内容:

select 
count(case when id= 1 then 1 end) One,
count(case when id= 2 then 1 end) Two,
count(case when id= 3 then 1 end) Three,
count(case when id= 4 then 1 end) Four,
count(case when id= 5 then 1 end) Five,
count(case when id= 6 then 1 end) Six,
count(case when id= 7 then 1 end) Seven,
count(case when id= 8 then 1 end) Eight,
count(case when id= 9 then 1 end) Nine,
count(case when id= 10 then 1 end) Ten
from data;

结果:

ONE TWO  THREE  FOUR    FIVE    SIX SEVEN   EIGHT   NINE    TEN
4   1      0      0       0       0    0      0        0    1

SQLFiddle 演示

无需旋转

您可以使用以下内容:

select id, count(*) as Count from data group by id;

结果将显示为:

id, count
1            5 
2            8
3            9
4            15
于 2013-07-26T08:23:03.697 回答
0

此查询可能有用

SELECT 
    COUNT(*) 
FROM [table] 
GROUP BY [column_id] 
HAVING id >= 1 && id <= 10
于 2013-07-26T08:23:44.947 回答