选择是否有超过n个结果但有条件

时间:2014-12-17 04:43:34

标签: sql-server

不幸的是,类似的问题并没有包括很少的条件和#34;对于这种情况。

所以,我的表是:

| TimeId | Work_Role | User_Name |
----------------------------------
|    1   | users     | Oran      | *
|    2   | admin     | Ray       |
|    3   | users     | Oran      | *
|    4   | servs     | Amit      |
|    5   | admin     | Oran      |
|    6   | users     | Ray       |
|    7   | users     | Oran      | *
|    8   | servs     | Amit      |
|    9   | admin     | Oran      |
|   10   | users     | Oran      | *

我希望显示user_name =" Oran"的列表。和Work_Role ="用户"只要表格中有超过2个。

在这种情况下,我希望看到:

| TimeId | Work_Role | User_Name |
----------------------------------
|    1   | users     | Oran      | 
|    3   | users     | Oran      | 
|    7   | users     | Oran      | 
|   10   | users     | Oran      |

我试图在这里使用HAVING类似的问题,但它没有提供任何结果。我假设可能多个条件与它有关。

所以这就是"主要"代码:

SELECT *
FROM Table
WHERE Work_Role = 'users' AND User_Name = 'Oran'

如果有超过2个结果,我如何添加条件才能选择?...

3 个答案:

答案 0 :(得分:1)

只需使用此查询即可使用

SELECT UserName,Work_Role
   FROM yourtableName
   WHERE UserName='oran' AND Work_Role='users'
   GROUP BY UserName,Work_Role
   Having Count(Work_Role)>2 

答案 1 :(得分:0)

SELECT * 
FROM   users u JOIN 
        (  SELECT user_name 
           FROM   users 
           GROUP BY user_name 
           HAVING count(user_name) > 2
        ) AS u2 ON u.user_name = u2.user_name

-

example

答案 2 :(得分:0)

示例数据

CREATE TABLE yourTable(
    TimeId      INT,
    Work_Role   VARCHAR(10),
    User_Name   VARCHAR(10)
)
INSERT INTO yourTable VALUES
(1, 'users', 'Oran'),
(2, 'admin', 'Ray'),
(3, 'users', 'Oran'),
(4, 'servs', 'Amit'),
(5, 'admin', 'Oran'),
(6, 'users', 'Ray'),
(7, 'users', 'Oran'),
(8, 'servs', 'Amit'),
(9, 'admin', 'Oran'),
(10, 'users', 'Oran');

解决方案#1:使用CTE

WITH cte AS(
    SELECT *, cc = COUNT(*) OVER(PARTITION BY Work_Role, User_Name) FROM yourTable
)
SELECT
    TimeId,
    Work_Role,
    User_Name
FROM cte
WHERE
    Work_Role = 'users' 
    AND User_Name = 'Oran'
    AND cc > 2

解决方案#2:使用加入

SELECT
    t.*
FROM yourTable t
INNER JOIN(
    SELECT
        Work_Role,
        User_Name,
        cc = COUNT(*)
    FROM yourTable
    GROUP BY Work_Role, User_Name
)g
    ON t.Work_Role = g.Work_Role
    AND t.User_Name = g.User_Name
WHERE
    t.Work_Role = 'users' 
    AND t.User_Name = 'Oran'
    AND cc > 2

清理样本数据

DROP TABLE yourTable