多列上的SELECT COUNT(DISTINCT ...)错误?

时间:2013-09-23 21:11:12

标签: sql sql-server tsql

我有一个表,VehicleModelYear,包含列id,年份,品牌和型号。

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

SELECT DISTINCT make, model
FROM VehicleModelYear

SELECT COUNT(DISTINCT make)
FROM VehicleModelYear

但是,此查询不起作用

SELECT COUNT(DISTINCT make, model)
FROM VehicleModelYear

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

3 个答案:

答案 0 :(得分:35)

COUNT()中的

SQL Server接受以下语法

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

您可以使用子查询返回可以计算的唯一makemodel集。

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

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

答案 1 :(得分:18)

尝试将它们合并到一个字段中:

SELECT COUNT(DISTINCT make + ' ' + model)
FROM VehicleModelYear

答案 2 :(得分:5)

语法是有效的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 ;