【问题标题】:Selecting distinct column of a distinct column using SQL Server使用 SQL Server 选择不同列的不同列
【发布时间】:2018-03-21 02:53:44
【问题描述】:

我正在尝试仅选择 2 个不同的列来确定我的查询中显示的记录。列 userid 能够拥有多个房屋,这意味着 userid 目前可以多次出现。但是,我只关心它们是否特定于房子的颜色,所以我希望 userid 列与 House 列不同,而其余行可以保持为该行中的任何内容。

Select UserID, House, NumOfPpl, NumOfCars 
from people

结果:

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

需要:

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

我已经使用 cte 去除了重复的用户 ID,但是我怎样才能去除用户 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

【问题讨论】:

  • 你试过使用 groupby 吗?

标签: sql sql-server


【解决方案1】:

将您希望唯一的值放在partition by 中。所以,我想你想要userID, house 那里。 order by 没有区别:

with cte AS (
    select p.* 
           row_number() over (partition by userID, house order by house) AS seqnum
    from people p
)

select userid, house, numofppl, numofcars
from cte 
where seqnum = 1;

【讨论】:

  • 5 星答案!太感谢了。我不知道一个分区可以包含多个值!
【解决方案2】:

这个查询可以工作。

从人中选择 * WHERE house = ANY (SELECT DISTINCT house FROM people);

试试这个,我想这应该可以。

【讨论】:

    猜你喜欢
    • 2014-06-13
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多