使用SQL Server选择不同的列

时间:2018-03-19 20:11:47

标签: sql sql-server

我试图只选择一个不同的列来确定我的查询中显示的记录。列userid能够拥有多个房屋,这意味着当前可以多次出现用户ID。但是,我只关心他们是否拥有一个房子,所以我希望userid列是不同的,而其余行可以保持为该行内的任何内容。

Select UserID, House, NumOfPpl, NumOfCars 
from people

结果:

userID  House  NumOfPpl  NumOfCars 
-----------------------------------
1a        red    3          2
1a        blue   1          1
2a        red    3          3
3a        green  4          6
3ab       red    2          1
3ab       blue   2          1

需要:

userID  House  NumOfPpl  NumOfCars
----------------------------------
1a        red    3          2
2a        red    3          3
3a        green  4          6
3ab       red    2          1

看起来当我尝试对userID进行计数时,每行都会得到一个'1'的值,因为它正在计算房子的数量。

Select UserID, count(UserId), House, NumOfPpl, NumOfCars 
from people 
group by UserID, House, NumOfPpl, NumOfCars

1 个答案:

答案 0 :(得分:1)

如果必须包含所有列,请按用户ID

从每个分区中选择第一条记录
 ;with cte AS (
    select userid, 
    house, 
    numofppl, 
    numofcars, 
    row_number() OVER(partition by userID order by house) AS rowcounter
    FROM people
)

SELECT userid, house, numofppl, numofcars
from cte 
WHERE rowcounter = 1
相关问题