2013-09-23 133 views
16

我有一張表,VehicleModelYear,包含列id,年份,品牌和型號。多列上出現SELECT COUNT(DISTINCT ...)錯誤?

以下兩個查詢按預期工作:

SELECT DISTINCT make, model 
FROM VehicleModelYear 

SELECT COUNT(DISTINCT make) 
FROM VehicleModelYear 

然而,此查詢不起作用

SELECT COUNT(DISTINCT make, model) 
FROM VehicleModelYear 

很明顯的答案是第一個查詢返回結果的數量,但只是想知道這個語法有什麼問題,或者爲什麼它不起作用。

+0

可能重複](http://stackoverflow.com/questions/1471250/counting-distinct-over-multiple-c olumns) –

回答

32

SQL ServerCOUNT()接受以下語法

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

+0

也適用於MySQL,謝謝! – by0

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 ; 
+0

有道理,謝謝! – csab

18

嘗試將它們組合成一個單一的領域:計數在多個列DISTINCT的

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

clever':)'..... –

+9

或'SELECT COUNT(DISTINCT CHECKSUM(make,model)) FROM VehicleModelYear' –

+0

@TimSchmelter整潔! –