SQL 具有多个 Having 条件的计数聚合

SQL Count Aggregate with Multiple Having Conditions

我正在尝试编写一个 SQL 查询,仅 returns 员工在同一日期有多个交易(count(TransactionDate) > 1),但交易发生在不同的商店身份证。我正在尝试结合使用计数聚合和具有,但似乎无法 return 正确的值。 temp table 是更好的方法,还是子查询?我的以下查询没有 returning 准确记录。任何帮助表示赞赏。谢谢!

EmployeeID  | StoreID | TransactionDate
--------------------------------------
     1      |   1     | 2016-09-09    --should be returned
--------------------------------------
     1      |   2     | 2016-09-09    --should be returned
--------------------------------------
     1      |   3     | 2016-09-09    --should be returned
--------------------------------------
     1      |   1     | 2016-09-18    --should not be returned
--------------------------------------
     2      |   1     | 2016-09-09    --should not be returned
--------------------------------------
     2      |   1     | 2016-09-09    --should not be returned
--------------------------------------
     3      |   1     | 2016-09-09    --should not be returned
--------------------------------------
     4      |   5     | 2016-09-09    --should be returned
 --------------------------------------
     4      |   6     | 2016-09-09    --should be returned

select top 1000 EmployeeID, StoreID, TransactionDate, count(StoreID)[StoreCount], count(TransactionDate)[Transaction Count]
from myTable  
group by EmployeeID, StoreID, TransactionDate
having count(StoreID) > 1 and count(TransactionDate) > 1
order by TransactionDate desc
SELECT t.*
FROM
    (
       SELECT
          EmployeeId, TransactionDate
       FROM
          Table
       GROUP BY
          EmployeeId, TransactionDate
       HAVING
          COUNT(DISTINCT StoreId) > 1
    ) e
    INNER JOIN Table t
    ON e.EmployeeId = t.EmployeeId
    AND e.TransactionDate = t.TransactionDate

实际上 window 函数在这里不会有太大帮助,因为关键是 COUNT(DISTINCT StoreId) 按 Employee & TransactionDate 分组,并且 COUNT(DISTINCT ) OVER () 是不允许的。所以派生的 table 是正确的方法,这种语法几乎适用于所有典型的 RDBMS。

如果您只想要员工:

SELECT DISTINCT EmployeeId
FROM myTable t
GROUP BY EmployeeId, TransactionDate
HAVING MIN(StoreId) <> MAX(StoreId);

这是 select distinctgroup by 一起使用的极少数情况之一。所以这种类型的查询是一个比较特殊的东西。