如何在SQL中的选定列上分组?

时间:2019-01-22 11:11:10

标签: sql-server

如何在选定列中按条件应用分组 我只想按条件对“ userdata”表的名称字段应用分组。

SELECT CAST(UserId AS varchar(255)) AS UserId,
       CAST(name AS varchar(255)) AS name,
       CAST(city AS varchar(255))
FROM "userdata"
WHERE name = 'Jhohn'
GROUP BY CAST(UserId AS varchar(255)),
         CAST(name AS varchar(255)),
         CAST(city AS varchar(255));

以上结果为

userId  name       city 
1       jhon       florida
2       sam        new york
3       sam        wales
4       thomas     new york

预期结果:

userId  name       city 
1       jhon       florida
2       sam        new york
4       thomas     new york

3 个答案:

答案 0 :(得分:1)

您可以像下面那样使用ROW_NUMBER()来实现所需的目的

SELECT * FROM
    (
       SELECT userid, 
           NAME, 
           city, 
           Row_number() OVER(partition BY NAME ORDER BY id) RN 
    FROM   userdata 
    )T
    WHERE  T.RN= 1 

我不确定您为什么将VARCHAR数据再次投射到VARCHAR?并且您在示例查询中放置了一个条件条件,该条件将过滤记录,而您不会获得所有记录。

答案 1 :(得分:1)

您可以像下面这样使用。

DECLARE @Table TABLE (UserId int, [Name] varchar(255), City varchar(255));
INSERT INTO @Table (UserId,[name], city)
VALUES(1,'Jhon', 'florida') 
,(2,'sam', 'New york')
,(3,'sam','wales')
,(4,'thomas','new york');

SELECT sq.userId, sq.Name, sq.City
FROM
(
    SELECT *, DENSE_RANK() OVER(PARTITION BY t.Name ORDER BY t.UserId) AS RNo
    FROM @Table AS t
) AS sq
WHERE sq.RNo = 1

答案 2 :(得分:1)

您也可以使用以下代码进行

DECLARE @Table TABLE (UserId int, [Name] varchar(255), City varchar(255));
INSERT INTO @Table (UserId,[name], city)
VALUES(1,'Jhon', 'florida') 
,(2,'sam', 'New york')
,(3,'sam','wales')
,(4,'thomas','new york');

Select t.* from @Table t
inner join (
SELECT MIN(UserId) as UserId, Name
FROM   @Table
GROUP BY
       Name
)a on t.UserId = a.UserId

您可以找到实时演示Here