25

对于某些人来说,它可能看起来很简单,但我就是无法理解。
我一遍又一遍地从同一个表中获得多个 MS-SQL SELECT 查询:

SELECT count(Page) as tAEC
FROM someTable
WHERE Page LIKE '%AEC%'

下一个

SELECT count(Page) as tTOL
FROM someTable
WHERE Page LIKE '%TOL%'

等等...

编写此查询的更有效方法是什么。我用谷歌搜索了一堆类似的问题,但我无法让它们中的任何一个起作用。因此,非常感谢任何帮助。

4

2 回答 2

79
SELECT sum(case when Page LIKE '%AEC%' then 1 end) as tAEC, 
    sum(case when Page LIKE '%TOL%' then 1 end) as tTOL 
FROM someTable 
于 2012-10-17T15:55:33.800 回答
7

你可以使用一个GROUP BY Page

SELECT
  Page
, COUNT(Page) as "nb"
FROM someTable
GROUP BY Page

你也可以做一个GROUP BY CASE...

SELECT
  CASE
    WHEN Page LIKE '%AEC%' THEN "AEC"
    WHEN Page LIKE '%TOL%' THEN "TOL"
    ELSE ""
  END AS "type"
, count(Page) as "nb"
FROM someTable
GROUP BY type

你也可以COUNT IF

SELECT
  COUNT(IF(Page LIKE '%AEC%', 1, NULL) THEN "AEC"
, COUNT(IF(Page LIKE '%TOL%', 1, NULL) THEN "TOL"
FROM someTable
于 2012-10-17T15:56:43.973 回答