語法是有效的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 ;
可能重複](http://stackoverflow.com/questions/1471250/counting-distinct-over-multiple-c olumns) –