如何设置查询SQL COUNT - 不同但值是唯一的

问题描述 投票:1回答:1

如何通过示例将正确的查询写入SQL语言?

在问SQL之前:

|     User       |    City    |
|----------------|------------|
| John Travolta  | New York   |
| Anonymous      | New Jersey |
| John Travolta  | New York   |
| Anonymous      | New Jersey |
| John Travolta  | New York   |
| Bill Gates     | New Haven  |

在询问SQL后会返回:

总记录:

New York - 1
New Jersey - 2
New Haven - 1

注意:

DISTINCT - 更多值John Travolta只计算1个DISTINCT - 一个值Anonymous将计数1个DISTINCT - 三个值Anonymous将计算3个DISTINCT - 五个值John Travolta将仅计数1个


请看ttps://www.w3schools.com/sql/trysql.asp?filename=trysql_select_no_distinct

然后:

SELECT country, count(DISTINCT city) as total_records FROM Customers WHERE country="Spain" GROUP BY country

在询问SQL之后我想要:

国家total_records西班牙5

因为仅在马德里的列中的值是唯一的。

sql unique distinct
1个回答
0
投票

试试这个:

SELECT City, COUNT(DISTINCT User2)
FROM 
    (SELECT City, User
    , CASE WHEN User= 'Anonymous' THEN CAST(ROW_NUMBER() OVER (ORDER BY City) AS VARCHAR(10)) ELSE User END AS User2 
    FROM MyTable) a --Replace MyTable with the name of your table
GROUP BY City

它为每个“匿名”条目分配一个唯一的数字值,然后计算其中的不同数量或非匿名名称。

© www.soinside.com 2019 - 2024. All rights reserved.