在列上应用多个条件

时间:2013-09-18 06:49:48

标签: sql count

我的表格如下所示。

ID  Task
1   Search
2   Basic
3   Natural search
4   Query1
5   query2
6   Query3
7   Sample1
8   sample2
9   test1
10  test2
11  test3

现在我需要计算任务列中的值,其中task =(search,Basic,Natural serach)和task =(query1,Query2,Query3)和task =(sample1,sample3)和task =(test1,test2) ,TEST3)。我想分别存储每个计数,如

count(search),count(Query),count(sample),count(test)

2 个答案:

答案 0 :(得分:1)

如果您希望结果为行:

SELECT 'Search' AS Task, COUNT(ID) AS Counts
  FROM MyTable
 WHERE task IN('search', 'Basic', 'Natural search')
UNION ALL
SELECT 'Query', COUNT(ID)
  FROM MyTable
 WHERE task IN('Query1', 'Query2', 'Query3')
UNION ALL
SELECT 'Sample', COUNT(ID)
  FROM MyTable
 WHERE task IN('sample1', 'sample2')
UNION ALL
SELECT 'Test', COUNT(ID)
  FROM MyTable
 WHERE task IN('test1', 'test2', 'test3');

输出:

|   TASK | COUNTS |
|--------|--------|
| Search |      3 |
|  Query |      3 |
| Sample |      2 |
|   Test |      3 |

如果您希望结果为列:

SELECT
  SUM(CASE WHEN Task = 'Search' THEN  1 
            WHEN Task = 'Basic' THEN  1 
            WHEN Task = 'Natural search' THEN  1 
            ELSE 0 END) AS SEARCH 
  ,SUM(CASE WHEN Task = 'Query1' THEN  1 
            WHEN Task = 'Query2' THEN  1 
            WHEN Task = 'Query3' THEN  1 
            ELSE 0 END) AS Query 
  ,SUM(CASE WHEN Task = 'Sample1' THEN  1 
            WHEN Task = 'sample2' THEN  1 
            ELSE 0 END) AS Sample
  ,SUM(CASE WHEN Task = 'test1' THEN  1 
            WHEN Task = 'test2' THEN  1 
            WHEN Task = 'test3' THEN  1 
            ELSE 0 END) AS Test
FROM MyTable;

输出:

| SEARCH | QUERY | SAMPLE | TEST |
|--------|-------|--------|------|
|      3 |     3 |      2 |    3 |

请参阅this SQLFiddle

答案 1 :(得分:0)

在一行中尝试使用以下结果:

SELECT
(SELECT COUNT(*)
FROM Table
WHERE task = 'search' or task = 'Basic' or task = 'natural search') AS CountSearch,
(SELECT COUNT(*)
FROM Table
WHERE task = 'Query1' or task = 'Query2' or task = 'Query3') AS CountQuery,
(SELECT COUNT(*)
FROM Table
WHERE task = 'sample1' or task = 'sample2') AS CountSample,
(SELECT COUNT(*)
FROM Table
WHERE task = 'test1' or task = 'test2' or task = 'test3') AS CountTest

以下几行结果如下:

SELECT 'CountSearch', COUNT(*)
FROM Table
WHERE task = 'search' or task = 'Basic' or task = 'natural search'
UNION ALL
SELECT 'CountQuery', COUNT(*)
FROM Table
WHERE task = 'Query1' or task = 'Query2' or task = 'Query3'
UNION ALL
SELECT 'CountSample', COUNT(*)
FROM Table
WHERE task = 'sample1' or task = 'sample2'
UNION ALL
SELECT 'CountTest', COUNT(*)
FROM Table
WHERE task = 'test1' or task = 'test2' or task = 'test3'

我重命名了你的列,因为你不能在sql语句中使用括号作为columnname。