-1

我的表如下所示。

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) and task=(query1,Query2,Query3) and task=(sample1,sample) and task=(test1,test2,test3) . 我想分别存储每个计数

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

2 回答 2

1

In case you want the result as rows:

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

Output:

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

In case you want the result as columns:

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;

Output:

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

See this SQLFiddle

于 2013-09-18T07:12:52.113 回答
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 语句中使用括号作为列名。

于 2013-09-18T06:56:44.790 回答