2017-11-10 87 views
0

我想細化一個查詢甚至進一步闡述結果集。 我有一張桌子Logenter image description here選擇具有特定計數的記錄

我每天早上運行這個腳本。

SELECT [90DayTally] = COUNT(AssociateName) 
, AssociateName 
, Supervisor 
FROM [DailyAttendance].[dbo].[Log] 
Where EventDate >= dateadd(day, datediff(day, 0, getdate()), -90) 
group by AssociateName, Supervisor 
having COUNT(associatename)>4 
Order By [90DayTally] Desc 

這給管理人員看到了誰在搞亂(LOL)所以這是查詢的結果。

90DayTally AssociateName  Supervisor 
7   Carlos Silva  Karla Vivas 
6   Luz Carmen Garcia Cynthia Perez 
5   Daniel Lockington Damian Vasquez 

我也想向高層管理人員展示這些colum計數究竟是什麼。 下面我顯示的是什麼,我想看到一個例子,我有到達致這現在

select * 
FROM [DailyAttendance].[dbo].[Log] 
Where EventDate >= dateadd(day, datediff(day, 0, getdate()), -90) 
and AssociateName in ('Carlos Silva', 'Luz Carmen Garcia', 'Daniel Lockington') 
order by AssociateName Asc 

這是工作顯示這些結果的基本的方式,但我有這個每天早上做的,改變了AssociateName非常乏味。

enter image description here

我已經嘗試了子查詢,但顯然incorrectly.Is有辦法可以達致這無需輸入where子句下每個AssociateName

回答

1

您可以使用您現有的查詢作爲子查詢並替換IN子句的硬編碼值。

事情是這樣的,也許: -

select * 
FROM [DailyAttendance].[dbo].[Log] 
Where EventDate >= dateadd(day, datediff(day, 0, getdate()), -90) and AssociateName in (
SELECT AssociateName FROM (
SELECT [90DayTally] = COUNT(AssociateName), AssociateName, Supervisor 
FROM [DailyAttendance].[dbo].[Log] 
Where EventDate >= dateadd(day, datediff(day, 0, getdate()), -90) 
group by AssociateName, Supervisor 
having COUNT(associatename)>4 
) AS DATA 
) order by AssociateName Asc 
+0

接近我試過。這隻需要從sub中刪除'order by'子句。謝謝 – DRUIDRUID