对于下表,我想写一个CASE语句:对于同一个ID,如果未来有多个日期,并且Renew="是的;用"Action"填充Action列;需要审查";。我假设应该使用OVER(PARTITION BY(,但不确定是如何使用的
原始表格:
ID | 日期 | 续订|
---|---|---|
123 | 06-01-2023 | 是|
123 | 06-01-2022 | 是 |
123 | 06-01-2021 | 是//tr>
尝试使用条件SUM((来计算标记为"更新";,与未来日期。然后返回";Needs Review";如果计数是>1.
您没有指定dbms,但尝试
SQL Server:
SELECT t.*
, IF(t.NumToReview > 1, 'Needs Review', NULL) AS [Action]
FROM (
SELECT
Id
, [Date]
, [Renew]
, SUM( CASE WHEN Date > cast(getDate() as date)
AND Renew = 'Yes' THEN 1
ELSE 0
END
) OVER(PARTITION BY Id) AS NumToReview
FROM YourTable
) t
MySQL:
SELECT t.*
, IF(t.NumToReview > 1, 'Needs Review', NULL) AS Action
FROM (
SELECT
Id
, `Date`
, Renew
, SUM( CASE WHEN `Date` > CAST(now() AS DATE)
AND Renew = 'Yes' THEN 1
ELSE 0
END
) OVER(PARTITION BY Id) AS NumToReview
FROM YourTable
) t
结果:
Id | 日期 | 续订NumToReview操作 | |
---|---|---|---|
123 | 06-01-2023 | 是2 | 需要审查|
123 | 06-01-2022 | 是 | 2 | 需求审查
123 | 06-01-2021 | 是2 | 需要审查