SQL Group By - 选择两列

时间:2010-07-02 00:42:23

标签: sql mysql group-by having

我有一个包含以下列的用户表:

| User_ID  (int) | Name (varchar) |   Age (int)  |  Experience_Level (int) |

我想创建一个sql查询来输出在年龄和经验的组合中不是唯一的人的所有ID。

到目前为止我的代码:

SELECT Count(*), User_ID FROM Users 
GROUP BY Age,Experience_Level
HAVING Count(*) > 1

显然这是不完整的,这将对非唯一用户进行分组,但不会告诉我所有的User_ID。

提前感谢您的帮助!

4 个答案:

答案 0 :(得分:3)

这是一个否定的逻辑查询:

SELECT *
FROM Users
WHERE UserID not in
(
SELECT MIN(UserID)
FROM Users
GROUP BY Age, Experience_Level
HAVING COUNT(*) = 1
)

答案 1 :(得分:2)

由于您需要有关多个用户组的信息,您希望如何返回此数据?在包含逗号分隔的user_id值列表的字符串中?

您没有使用您使用的SQL数据库标记您的问题。

如果您使用MySQL或SQLite,则可以使用内置的GROUP_CONCAT()函数:

SELECT Count(*), GROUP_CONCAT(User_ID) AS User_List FROM Users 
GROUP BY Age,Experience_Level
HAVING Count(*) > 1

默认情况下,GROUP_CONCAT()用逗号分隔值。如果您希望以其他方式格式化,请参阅手册。

其他SQL供应商还有其他解决方案。 Stack Overflow上出现了很多次这个问题:

答案 2 :(得分:1)

SELECT t.User_ID, t.Age, t.Experience_Level
FROM Users t INNER JOIN 
    (SELECT Age, Experience_Level
    FROM Users
    GROUP BY Age, Experience_Level
    HAVING Count(*) > 1) d ON t.Age = d.Age AND t.Experience_Level = d.Experience_Level

测试脚本:

create table Users (
User_ID int,
Name varchar(50),
Age int,
Experience_Level int
)

insert into Users (User_ID, Name, Age, Experience_Level) values (1, 'A', 33, 1)
insert into Users (User_ID, Name, Age, Experience_Level) values (2, 'B', 37, 1)
insert into Users (User_ID, Name, Age, Experience_Level) values (3, 'C', 33, 1)
insert into Users (User_ID, Name, Age, Experience_Level) values (4, 'D', 35, 2)
insert into Users (User_ID, Name, Age, Experience_Level) values (5, 'E', 33, 1)
insert into Users (User_ID, Name, Age, Experience_Level) values (6, 'F', 35, 2)
insert into Users (User_ID, Name, Age, Experience_Level) values (7, 'G', 18, 1)

答案 3 :(得分:1)

理论上,你想要的是这样的,但不幸的是SQL Server不允许它:

SELECT * FROM Users 
WHERE (Age, Experience_Level) IN
(
    SELECT Age, Experience_Level
    FROM Users  
    GROUP BY Age,Experience_Level 
    HAVING Count(*) > 1 
)

相反,你必须满足于加入子查询:

SELECT Users.* FROM Users 
INNER JOIN 
(
    SELECT Age, Experience_Level
    FROM Users  
    GROUP BY Age,Experience_Level 
    HAVING Count(*) > 1 
) subq 
    ON Users.Age = subq.Age
    AND Users.Experience_Level = subq.Experience_Level