我在 DB2 上,我想转换上面的语句,其中将数字日期 (yyyymmdd) TXDTDBVL 与 CURRENT DATE 进行比较,以将当前月份作为条件:
SELECT
'86',
B.GGCDOGA,
B.GGCDPAT1,
CASE WHEN B.GGNOUGRAT <> ' ' THEN B.GGNOUGRAT ELSE B.GGNOUG END AS NOUG,
90,
SUM(A.TXMTLOYANX)
FROM
IKOS_F.UGCSALP A,
IKOS_F.UGP B
WHERE
TXDTDBVL >= YEAR(CURRENT DATE) * 10000 + MONTH(CURRENT DATE) * 100 + 01 AND
TXDTDBVL <= YEAR(CURRENT DATE) * 10000 + MONTH(CURRENT DATE) * 100 + 31
AND (
(B.GGCDOGA, B.GGNOUG) IN (
SELECT
DISTINCT IWCDORG,
IWCDLOGT
FROM
IKOS_F.IMWXRUP
)
OR (B.GGCDOGA, B.GGNOUGRAT) IN (
SELECT
DISTINCT IWCDORG,
IWCDLOGT
FROM
IKOS_F.IMWXRUP
)
)
AND A.TXCDOGA = B.GGCDOGA
AND A.TXNOUG = B.GGNOUG
AND A.TXCDTTARIF = B.GGCDTTARIF
GROUP BY
B.GGCDOGA,
B.GGCDPAT1,
CASE WHEN B.GGNOUGRAT <> ' ' THEN B.GGNOUGRAT ELSE B.GGNOUG END;
将数字日期 TXDTDBVL 与 MAX(CURRENT DATE, 数字日期 B.GGDTMSUG) 进行比较:
SELECT
'86',
B.GGCDOGA,
B.GGCDPAT1,
CASE WHEN B.GGNOUGRAT <> ' ' THEN B.GGNOUGRAT ELSE B.GGNOUG END AS NOUG,
90,
SUM(A.TXMTLOYANX)
FROM
IKOS_F.UGCSALP A,
IKOS_F.UGP B
WHERE
TXDTDBVL >= YEAR(MAX(CURRENT DATE,B.GGDTMSUG)) * 10000 + MONTH(MAX(CURRENT DATE,B.GGDTMSUG)) * 100 + 01 AND
TXDTDBVL <= YEAR(MAX(CURRENT DATE,B.GGDTMSUG)) * 10000 + MONTH(MAX(CURRENT DATE,B.GGDTMSUG)) * 100 + 31
AND (
(B.GGCDOGA, B.GGNOUG) IN (
SELECT
DISTINCT IWCDORG,
IWCDLOGT
FROM
IKOS_F.IMWXRUP
)
OR (B.GGCDOGA, B.GGNOUGRAT) IN (
SELECT
DISTINCT IWCDORG,
IWCDLOGT
FROM
IKOS_F.IMWXRUP
)
)
AND A.TXCDOGA = B.GGCDOGA
AND A.TXNOUG = B.GGNOUG
AND A.TXCDTTARIF = B.GGCDTTARIF
GROUP BY
B.GGCDOGA,
B.GGCDPAT1,
CASE WHEN B.GGNOUGRAT <> ' ' THEN B.GGNOUGRAT ELSE B.GGNOUG END;
我尝试过
HAVING
与
SELECT MAX(TXDTDBVL) FROM (VALUES (CURRENT DATE),(B.GGDTMSUG))
但是我迷路了...
使用正确的
DATE
数据类型时,管理和比较日期通常很简单。如果您使用 NUMERIC
值模拟日期,则会变得更加棘手。您可以使用 CTE 来预处理日期并将所有内容带入数字域。
例如,您可以这样做:
with
p (cd) as (
select
year(CURRENT DATE) * 10000 + month(CURRENT DATE) * 100 + day(CURRENT DATE)
from sysibm.sysdummy1
)
select *
from t, p
where txdtdbvl between
trunc(greatest(p.cd, t.ggdtmsug) / 100) * 100 + 01 and
trunc(greatest(p.cd, t.ggdtmsug) / 100) * 100 + 31;
在此示例中,第一行和第三行按预期选择。第二个不符合条件。
请参阅 db<>fiddle 处的运行示例。