挑选具有最大序号= -1的Empid 8个季度

时间:2017-06-14 01:07:39

标签: sql sql-server

我有一个表“摘要”,其中包含以下信息

Sumid(pk) Empid(fk)  Year   Quarter    Seqnumber amount
101        1001      2015      1          -1      1000
102        1001      2015      1           0      2000
103        1001      2015      1           1      3000
104        1001      2015      1           2      4000
105        1002      2015      1           -1     6000
105        1002      2015      2           -1     7000
105        1002      2015      3           -1     8000
105        1002      2015      4           -1     9000
105        1002      2016      1           -1     10000
105        1002      2016      2           -1     11000
105        1002      2016      3           -1     12000
105        1002      2016      4           -1     13000
Output:

Empid(fk)
1002

商业规则:我们需要选择最大(Seqnumber)= - 1的Empid 8个季度(向后) 即在这个例子1002从2016年第四季度开始到2015年第一季度它只有“-1” as max(seqnumber),所以我们需要选择那个empid。

3 个答案:

答案 0 :(得分:1)

在SQL Server 2012+中,您可以使用窗口函数计算它们:

select distinct empid;
from (select t.*,
             max(seqnum) over (partition by empid rows between 7 preceding and current row) as max_seqnum8
      from t
     ) t
where max_seqnum8 = -1

答案 1 :(得分:0)

如果季度> = 8

,您可以使用此功能
SELECT 
Empid
FROM summary
WHERE Empid NOT IN 
(
SELECT Empid FROM summary GROUP BY Empid HAVING MAX(Seqnumber) <> -1
)
GROUP BY Empid
HAVING COUNT(*) >= 8

如果四分之一= 8

,您可以使用此功能
SELECT 
Empid
FROM summary
WHERE Empid NOT IN 
(
SELECT Empid FROM summary GROUP BY Empid HAVING MAX(Seqnumber) <> -1
)
GROUP BY Empid
HAVING COUNT(*) = 8

答案 2 :(得分:0)

;With cte(Sumid,Empid,[Year],[Quarter],Seqnumber,amount)
AS
(
SELECT 101, 1001,2015 ,1,1  ,1000  Union all
SELECT 102, 1001,2015 ,1,0  ,2000  Union all
SELECT 103, 1001,2015 ,1,1  ,3000  Union all
SELECT 104, 1001,2015 ,1,2  ,4000  Union all
SELECT 105, 1002,2015 ,1,-1 ,6000  Union all
SELECT 105, 1002,2015 ,2,-1 ,7000  Union all
SELECT 105, 1002,2015 ,3,-1 ,8000  Union all
SELECT 105, 1002,2015 ,4,-1 ,9000  Union all
SELECT 105, 1002,2016 ,1,-1 ,10000 Union all
SELECT 105, 1002,2016 ,2,-1 ,11000 Union all
SELECT 105, 1002,2016 ,3,-1 ,12000 Union all
SELECT 105, 1002,2016 ,4,-1 , 13000 
)
SELECT TOP 1  Empid From
--MAX(CountSeqnumber)OVER(PARTITION BY Empid ORDER BY Empid Desc) AS MaxSeq 
(
SELECT  *, COUNT(Seqnumber)Over(Partition by Empid Order by Empid) AS CountSeqnumber FROM cte
)Dt
ORDER BY Dt.Empid DESC