問題描述
我有一個表 VehicleModelYear,包含列 id、year、make 和 model.
I have a table, VehicleModelYear, containing columns id, year, make, and model.
以下兩個查詢按預期工作:
The following two queries work as expected:
SELECT DISTINCT make, model
FROM VehicleModelYear
SELECT COUNT(DISTINCT make)
FROM VehicleModelYear
但是,此查詢不起作用
SELECT COUNT(DISTINCT make, model)
FROM VehicleModelYear
很明顯答案是第一個查詢返回的結果數量,但只是想知道這個語法有什么問題或者為什么它不起作用.
It's clear the answer is the number of results returned by the first query, but just wondering what is wrong with this syntax or why it doesn't work.
推薦答案
COUNT()
在 SQL Server
接受以下語法
COUNT(*)
COUNT(colName)
COUNT(DISTINCT colName)
你可以有一個子查詢,它返回你可以計算的唯一的 make
和 model
集合.
You can have a subquery which returns unique set of make
and model
that you can count with.
SELECT COUNT(*)
FROM
(
SELECT DISTINCT make, model
FROM VehicleModelYear
) a
末尾的a"不是拼寫錯誤.這是一個別名,如果沒有它,SQL 將給出錯誤 ERROR 1248 (42000): 每個派生表必須有自己的別名
.
The "a" at the end is not a typo. It's an alias without which SQL will give an error ERROR 1248 (42000): Every derived table must have its own alias
.
這篇關于多列上的 SELECT COUNT(DISTINCT...) 錯誤?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!