选择具有特定计数的记录

时间:2017-11-10 23:51:01

标签: sql sql-server sql-server-2008

我正在尝试进一步细分查询以详细说明结果集。 我有一张表Log enter 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

我还想向高层管理人员展示这些列的确切含义。 下面我将展示一个我想看到的例子以及我现在必须实现的基本方法

 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

我尝试了一个子查询,但显然是错误的。有没有办法可以实现这一点,而无需在where子句下键入每个AssociateName

1 个答案:

答案 0 :(得分: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