21

我有一个表 VehicleModelYear,其中包含 id、year、make 和 model 列。

以下两个查询按预期工作:

SELECT DISTINCT make, model
FROM VehicleModelYear

SELECT COUNT(DISTINCT make)
FROM VehicleModelYear

但是,此查询不起作用

SELECT COUNT(DISTINCT make, model)
FROM VehicleModelYear

很明显,答案是第一个查询返回的结果数量,但只是想知道这个语法有什么问题或者为什么它不起作用。

4

3 回答 3

40

COUNT()inSQL Server接受以下语法

COUNT(*)
COUNT(colName)
COUNT(DISTINCT colName)

您可以有一个子查询,它返回唯一的集合make并且model您可以计算。

SELECT  COUNT(*)
FROM
        (
            SELECT  DISTINCT make, model
            FROM    VehicleModelYear
        ) a

最后的“a”不是错字。这是一个别名,没有它 SQL 将给出错误ERROR 1248 (42000): Every derived table must have its own alias

于 2013-09-23T21:13:36.393 回答
19

尝试将它们组合成一个字段:

SELECT COUNT(DISTINCT make + ' ' + model)
FROM VehicleModelYear
于 2013-09-23T21:15:33.597 回答
6

语法是有效的 SQL,但尚未在 SQL-Server 中实现。

尝试重写:

; WITH cte AS
  ( SELECT DISTINCT make, model
    FROM VehicleModelYear
  )
SELECT COUNT(*) AS total
FROM cte ; 

或者:

; WITH cte AS
  ( SELECT COUNT(DISTINCT model) AS cnt
    FROM VehicleModelYear
    GROUP BY make
  )
SELECT SUM(cnt) AS total
FROM cte ; 

或者:

; WITH cte AS
  ( SELECT NULL AS n
    FROM VehicleModelYear
    GROUP BY make, model
  )
SELECT COUNT(*) AS total
FROM cte ; 

最后,修改了上面的第二个和第三个查询,没有子查询:

SELECT DISTINCT
    SUM(COUNT(DISTINCT model)) OVER () AS total
FROM VehicleModelYear
GROUP BY make ;

SELECT DISTINCT COUNT(*) OVER () AS total
FROM VehicleModelYear
GROUP BY make, model ;

@Alexander Fedorenko的最新补充:

SELECT TOP (1)
    SUM(COUNT(DISTINCT model)) OVER () AS total
FROM VehicleModelYear
GROUP BY make ;

SELECT TOP (1) COUNT(*) OVER () AS total
FROM VehicleModelYear
GROUP BY make, model ;

或者:

; WITH cte AS
  ( SELECT DENSE_RANK() OVER(ORDER BY make, model) AS dr
    FROM VehicleModelYear
  )
SELECT MAX(dr) AS total
FROM cte ;
于 2013-09-23T21:14:33.040 回答