第一个帖子很抱歉!我:
<表类>
参与者价值规则 期 tbody><<tr>詹姆斯 0 规则1 2022-12-1 詹姆斯0 规则1 2022-01-1 詹姆斯1 规则1 2022-02-1 詹姆斯1 规则2 2022-12-1 詹姆斯1 规则2 2022-01-1 詹姆斯1 规则2 2022-02-1 表类>
以下建议对你有帮助
SELECT [TR1].[PARTICIPANT], SUM([TR1].[VALUE]) AS [VALUE], [TR1].[Period]
FROM
(
SELECT [PARTICIPANT], SUM([VALUE]) AS [VALUE], [RULE], [Period]
FROM [TABLE]
WHERE [RULE]='RULE 1'
GROUP BY [PARTICIPANT], [RULE], [Period]
) [TR1] LEFT JOIN
(
SELECT [PARTICIPANT], SUM([VALUE]) AS [VALUE], [RULE], [Period]
FROM [TABLE]
WHERE [RULE]='RULE 2'
GROUP BY [PARTICIPANT], [RULE], [Period]
) [TR2]
ON [TR1].[PARTICIPANT] = [TR2].[PARTICIPANT] AND
[TR1].[Period] = [TR2].[Period]
WHERE [TR1].[VALUE] >= COALESCE([TR2].[VALUE], 0)
GROUP BY [TR1].[PARTICIPANT], [TR1].[Period]
看起来您想要按PERIOD
进行条件聚合,然后仅按PARTICIPANT
进行分组
SELECT
t.PARTICIPANT,
COUNT(CASE WHEN t.Rule1 >= t.Rule2 THEN 1 END) Rule1MoreThan
FROM (
SELECT
t.PARTICIPANT,
t.PERIOD,
SUM(CASE WHEN t.[RULE] = 'RULE 1' THEN t.VALUE END) Rule1,
SUM(CASE WHEN t.[RULE] = 'RULE 2' THEN t.VALUE END) Rule2
FROM [TABLE] t
GROUP BY
t.PARTICIPANT,
t.PERIOD
) t
GROUP BY
t.PARTICIPANT;
,db<的在小提琴