在 table 中添加一个非重复计数列
Add a distinct count column in table
下面的场景是我想要完成的。我试过使用子查询失败。
基本上,我想要按日期对位置进行不同计数。当我尝试为每个位置分配 1 时,但我只想按日期为该位置的单个实例分配 1,为所有其他位置分配 0。
Date Name Location Distinct Count of locations by date
1-Feb Lands Orlando 1
1-Feb Magel Orlando 0
1-Feb Posel Orlando 0
1-Feb Orm Detroit 1
1-Feb Keel Los Angeles 1
---------------------------------------------
2-Feb Lands Orlando 1
2-Feb Magel Orlando 0
2-Feb Posel Orlando 0
2-Feb Orm Detroit 1
2-Feb Keel Los Angeles 1
我们可以在这里使用ROW_NUMBER
:
SELECT Date, Name, Location,
CASE WHEN ROW_NUMBER() OVER (PARTITION BY Date, Location ORDER BY Name) = 1
THEN 1 ELSE 0 END AS [Distinct Count of locations by date]
FROM yourTable
ORDER BY Date, Location, Name;
下面的场景是我想要完成的。我试过使用子查询失败。
基本上,我想要按日期对位置进行不同计数。当我尝试为每个位置分配 1 时,但我只想按日期为该位置的单个实例分配 1,为所有其他位置分配 0。
Date Name Location Distinct Count of locations by date
1-Feb Lands Orlando 1
1-Feb Magel Orlando 0
1-Feb Posel Orlando 0
1-Feb Orm Detroit 1
1-Feb Keel Los Angeles 1
---------------------------------------------
2-Feb Lands Orlando 1
2-Feb Magel Orlando 0
2-Feb Posel Orlando 0
2-Feb Orm Detroit 1
2-Feb Keel Los Angeles 1
我们可以在这里使用ROW_NUMBER
:
SELECT Date, Name, Location,
CASE WHEN ROW_NUMBER() OVER (PARTITION BY Date, Location ORDER BY Name) = 1
THEN 1 ELSE 0 END AS [Distinct Count of locations by date]
FROM yourTable
ORDER BY Date, Location, Name;