2

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

| 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

4 回答 4

3

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

SELECT *
FROM Users
WHERE UserID not in
(
SELECT MIN(UserID)
FROM Users
GROUP BY Age, Experience_Level
HAVING COUNT(*) = 1
)
于 2010-07-02T01:00:53.717 回答
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 上出现过很多次:

于 2010-07-02T00:55:53.250 回答
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)
于 2010-07-02T00:57:07.780 回答
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
于 2010-07-02T01:00:50.810 回答