SELECT GROUP查询生成的组数

时间:2015-11-26 08:48:54

标签: sql sql-server tsql sql-server-2014

我尝试了以下查询来选择GROUP BY查询产生的组数:

SELECT count(*)
FROM (
        SELECT count(*)
        FROM MyTable
        WHERE Col2 = 'x'
        GROUP BY Col1
     )

不幸的是,此查询无效:Incorrect syntax near ')'.

注意:我想得到一行(我已经找到了n次结果的解决方案,其中n =组计数)。

3 个答案:

答案 0 :(得分:9)

SELECT COUNT(*)
FROM (
    SELECT value = COUNT(*)
    FROM MyTable
    WHERE Col2 = 'x'
    GROUP BY Col1
) е

但我认为 - 您需要尝试此查询 -

SELECT COUNT(DISTINCT Col1)
FROM MyTable
WHERE Col2 = 'x'

答案 1 :(得分:7)

SELECT count(*)
FROM (
        SELECT 1 as dummy
        FROM MyTable
        WHERE Col2 = 'x'
        GROUP BY Col1
     ) dt

无需计算子查询中的行数,结果无论如何都会相同。

答案 2 :(得分:2)

你必须为列和表添加名称......

SELECT count(*) Total
FROM (
        SELECT count(*) Groups
        FROM MyTable
        WHERE Col2 = 'x'
        GROUP BY Col1
     ) a