2016-09-29 122 views
1

我正在嘗試編寫一個SQL查詢,該查詢僅返回在同一日期(count(TransactionDate)> 1)具有多個事務的僱員,但事務發生在不同的商店ID內。我試圖使用計數聚合和有,但似乎無法返回正確的值的組合。臨時表是一個更好的方法來做到這一點,或者一個子查詢?我下面的查詢沒有返回準確的記錄。任何幫助表示讚賞。謝謝!具有多個條件的SQL計數聚合

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

其中rdbms? sql-sever,mysql,oracle,...?它有所作爲,因爲這是窗口功能的完美例子 – Matt

回答

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)由員工& TransactionDate和COUNT(DISTINCT)分組OVER()是不允許的。所以派生表就是要走的路,這種語法將與幾乎所有典型的RDBMS一起工作。

+1

完美工作,謝謝! – AndrewC10

0

如果你只是想員工:

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

這是哪裏select distinct使用與group by的情形是很少見的。所以這種類型的查詢是一個相當特殊的事情。