我有以下数据:
如果某人每个日期同时具有“ Ramping”和“ Ramped”状态,那么我希望结果仅返回每个日期和状态为“ Ramped”的Person的SUM(小时)。否则,如果他们只有一个状态,则按日期和人返回SUM(小时)。我想要的结果是:
有什么建议吗?
答案 0 :(得分:0)
用例语句有条件地求和。假设只有两种状态:倾斜和倾斜
select Date, Person,
status = min(Status),
Hours = case when count(*) > 1
then sum(case when Status = 'Ramped' then Hours else 0 end)
else sum(Hours)
end
from yourtable
group by Date, Person
答案 1 :(得分:0)
这是未经测试的,因为OP的数据是图像(我不打算重新输入),但是,一种方法是使用NOT EXISTS
:
SELECT *
FROM YourTable YT
WHERE [Status] = 'Ramping'
OR NOT EXISTS (SELECT 1
FROM YourTable e
WHERE e.[Date] = YT.[Date]
AND e.Person = YT.Person
AND e.[Status] = 'Ramping');
答案 2 :(得分:0)
;WITH x(D,Pr,status,H) AS
(
SELECT GetDate(), 'A','1',8
UNION ALL
SELECT GetDate(), 'A','2',8
UNION ALL
SELECT GetDate()-1, 'A','1',8
)
SELECT TOP 1 WITH TIES
D,Pr,status,H
FROM x
ORDER BY
ROW_NUMBER() OVER (PARTITION BY D,Pr ORDER BY Status)
答案 3 :(得分:0)
由于“斜行<斜行”(按字母顺序排列),因此您可以按人员和日期对有序状态值进行编号,然后仅采用第一个,例如:
WITH numbering ([Date], Person, [Status], [Hours], Ranking) AS (
SELECT [Date], Person, [Status], [Hours]
, RANK() OVER (PARTITION BY [Date], Person ORDER BY [Status])
FROM YourTable WHERE [Status] IN ('Ramped', 'Ramping')
)
SELECT [Date], Person, [Status], [Hours]
FROM numbering
WHERE Ranking = 1;
答案 4 :(得分:0)
将原始表命名为table1。这是使用CTE的示例。
WITH cte AS (
SELECT [Date],[Person],[Status],sum([Hours]) as Hours,
row_number() OVER(PARTITION BY [Date],[Person] ORDER BY [Status]) AS rn
FROM [LEGALDB2].[dbo].[table1]
group by [Date],[Person],[Status]
)
select [Date],[Person],[Status],[Hours]
from cte
where rn=1