这里是样本数据 - 明智的
EMPL 1052017 2052017 3052017 4052017 5052017 6052017 7052017 8052017 9052017 10052017 11052017 12052017 13052017 14052017 15052017 'PENALTY > 3'
EMP1 P A A A A P P A A A A A P P P 3
EMP2 A A P A A A A A A A P A P P A 4
EMP3 A A A A A A A A A A A A A A A 12
帮助SQL获取作为处罚日的现有日期...... 逻辑:连续超过3次,1次罚款,如果是5天那么2次罚款,如果是6次,则继续进行。
以下必须达到的结果
EMPL P.DAYS A.DAYS PENALTY
EMP1 6 9 3
EMP2 3 11 4
EMP2 0 15 12
答案 0 :(得分:0)
如果您使用的是ms sql-server,则可以使用此方法。
我假设你的表将这些值保持为垂直。
-- Create Table & Sample Data
DECLARE @MyTable TABLE(
EMPL VARCHAR(10),
Value VARCHAR(10),
[Date] DATETIME )
INSERT INTO @MyTable VALUES
('EMP1', 'P', '20170501'),
('EMP1', 'A', '20170502'),
('EMP1', 'A', '20170503'),
('EMP1', 'A', '20170504'),
('EMP1', 'A', '20170505'),
('EMP1', 'P', '20170506'),
('EMP1', 'P', '20170507'),
('EMP1', 'A', '20170508'),
('EMP1', 'A', '20170509'),
('EMP1', 'A', '20170510'),
('EMP1', 'A', '20170511'),
('EMP1', 'A', '20170512'),
('EMP1', 'P', '20170513'),
('EMP1', 'P', '20170514'),
('EMP1', 'P', '20170515'),
('EMP2', 'A', '20170501'),
('EMP2', 'A', '20170502'),
('EMP2', 'P', '20170503'),
('EMP2', 'A', '20170504'),
('EMP2', 'A', '20170505'),
('EMP2', 'A', '20170506'),
('EMP2', 'A', '20170507'),
('EMP2', 'A', '20170508'),
('EMP2', 'A', '20170509'),
('EMP2', 'A', '20170510'),
('EMP2', 'P', '20170511'),
('EMP2', 'A', '20170512'),
('EMP2', 'P', '20170513'),
('EMP2', 'P', '20170514'),
('EMP2', 'A', '20170515'),
('EMP3', 'A', '20170501'),
('EMP3', 'A', '20170502'),
('EMP3', 'A', '20170503'),
('EMP3', 'A', '20170504'),
('EMP3', 'A', '20170505'),
('EMP3', 'A', '20170506'),
('EMP3', 'A', '20170507'),
('EMP3', 'A', '20170508'),
('EMP3', 'A', '20170509'),
('EMP3', 'A', '20170510'),
('EMP3', 'A', '20170511'),
('EMP3', 'A', '20170512'),
('EMP3', 'A', '20170513'),
('EMP3', 'A', '20170514'),
('EMP3', 'A', '20170515')
要确定连续缺席,您可以使用此查询。
;WITH CTE AS (
SELECT
( ROW_NUMBER() OVER(PARTITION BY EMPL ORDER BY [Date]) )
- ( ROW_NUMBER() OVER(PARTITION BY EMPL, Value ORDER BY [Date]) ) AS GRP
, *
FROM @MyTable
),
CTE_GRP AS (
SELECT EMPL, Value, GRP, COUNT(*) CNT
FROM CTE
GROUP BY EMPL, Value, GRP
)
SELECT EMPL,
SUM( CASE WHEN Value ='P' THEN CNT ELSE 0 END ) [P.DAYS],
SUM( CASE WHEN Value ='A' THEN CNT ELSE 0 END ) [A.DAYS],
SUM( CASE WHEN (CNT - 3) > 0 THEN CNT - 3 ELSE 0 END) PENALTY
FROM
CTE_GRP
GROUP BY EMPL
结果:
EMPL P.DAYS A.DAYS PENALTY
---------- ----------- ----------- -----------
EMP1 6 9 3
EMP2 4 11 4
EMP3 0 15 12