我需要在select语句中添加新列,其中包含所有记录中的最大年份(存储为文本),然后将其标记为CY / PY。桌子上总是只有两年。
year value
2019 value1
2019 value2
2018 value3
到目前为止,我已经尝试过了,但是它只返回那一行的max,而不是整列。
select year, value, IIF(year=MAX(year), 'CY', 'PY') AS "CY/PY" from table
预期:
year value CY/PY
2019 value1 CY
2019 value2 CY
2018 value3 PY
答案 0 :(得分:3)
我认为您想要一个窗口函数:
select year, value,
(case when year = MAX(year) over () then 'CY' else 'PY' end) AS "CY/PY"
from table
答案 1 :(得分:1)
尝试将MAX
用作分析函数:
WITH cte AS (
SELECT year, value, MAX(year) OVER () AS max_year
FROM yourTable
)
SELECT
year,
value,
IIF(year = max_year, 'CY', 'PY') AS "CY/PY"
FROM cte;
答案 2 :(得分:1)
尝试在IIF中使用子查询:
select year, value, IIF(year=(select MAX(year) from table), 'CY', 'PY') AS "CY/PY" from table