SELECT COUNT(DISTINCT… ) error on multiple columns?

后端 未结 3 2188
囚心锁ツ
囚心锁ツ 2021-02-12 19:18

I have a table, VehicleModelYear, containing columns id, year, make, and model.

The following two queries work as expected:

SELECT DISTINCT make, model
F         


        
3条回答
  •  忘掉有多难
    2021-02-12 19:34

    The syntax is valid SQL but has not been implemented in SQL-Server.

    Try a rewrite:

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

    or:

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

    or:

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

    And finally, the 2nd and 3rd query above modified, without subqueries:

    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 ;
    

    Late additions by @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 ;
    

    or:

    ; WITH cte AS
      ( SELECT DENSE_RANK() OVER(ORDER BY make, model) AS dr
        FROM VehicleModelYear
      )
    SELECT MAX(dr) AS total
    FROM cte ;
    

提交回复
热议问题