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

时间:2016-09-29 00:10:08

标签: sql count having-clause

我正在尝试编写一个SQL查询,该查询仅返回在同一日期有多个事务的员工(count(TransactionDate)> 1),但事务发生在不同的商店ID中。我试图使用count聚合和having的组合,但似乎无法返回正确的值。临时表是更好的方法吗,或者可能是子查询?我的下面的查询没有返回准确的记录。任何帮助表示赞赏。谢谢!

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

2 个答案:

答案 0 :(得分:1)

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

实际上窗口函数在这里不会有很多帮助,因为关键是COUNT(DISTINCT StoreId)由Employee&不允许使用TransactionDate和COUNT(DISTINCT)OVER()。因此,派生表是可行的方法,这种语法几乎适用于所有典型的RDBMS。

答案 1 :(得分:0)

如果您只是想要员工:

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

这是select distinctgroup by一起使用的极少数情况之一。所以这种类型的查询是一件非常特别的事情。

相关问题