我有一个让我困惑的简单查询。似乎MAX功能不起作用,但我确定我只是做错了。
如下所示,我得到2条记录,而不仅仅是一条记录。每个记录都有不同的FHUK01值,所以我输入MAX函数来拉出两者中较大的一个,但它似乎不起作用。
非常感谢任何帮助。
SELECT MAX(CRPDTA.F4981.FHUK01) AS "UID",
CRPDTA.F4981.FHSHPN,
CRPDTA.F4981.FHRTDQ,
CRPDTA.F4981.FHUOM,
CRPDTA.F4981.FHCGC1
FROM CRPDTA.f4981
WHERE crpdta.f4981.FHSHPN=4577085
AND CRPDTA.F4981.FHCGC1 = 'DIS'
GROUP BY CRPDTA.F4981.FHUK01,
CRPDTA.F4981.FHSHPN,
CRPDTA.F4981.FHRTDQ,
CRPDTA.F4981.FHUOM,
CRPDTA.F4981.FHCGC1;
示例查询输出:
UID FHSHPN FHRTDQ FHUOM FHCGC1
7502828 4577085 630000 MI DIS
7502827 4577085 0 DIS
答案 0 :(得分:2)
您正在GROUPing BY
列MAX
:
GROUP BY CRPDTA.F4981.FHUK01
你可能不想这样做。
答案 1 :(得分:0)
由于swasheck在他的帖子中提到,因为您在查询中有多个分组集,所以您将只获得多行。
如果,您希望获得与最大FHUK01相对应的数据。可能你需要的是:
Select CRPDTA.F4981.FHUK01,
CRPDTA.F4981.FHSHPN,
CRPDTA.F4981.FHRTDQ,
CRPDTA.F4981.FHUOM,
CRPDTA.F4981.FHCGC1
from crpdata.f4981
where f4981.fhuk01= (SELECT MAX(CRPDTA.F4981.FHUK01)
FROM CRPDTA.f4981
WHERE crpdta.f4981.FHSHPN=4577085
AND CRPDTA.F4981.FHCGC1 = 'DIS');
答案 2 :(得分:0)
尝试此查询:
SELECT MAX(CRPDTA.F4981.FHUK01) AS "UID",
CRPDTA.F4981.FHSHPN,
CRPDTA.F4981.FHRTDQ,
CRPDTA.F4981.FHUOM,
CRPDTA.F4981.FHCGC1
FROM CRPDTA.f4981
WHERE crpdta.f4981.FHSHPN=4577085
AND CRPDTA.F4981.FHCGC1 = 'DIS'
GROUP BY
CRPDTA.F4981.FHSHPN,
CRPDTA.F4981.FHRTDQ,
CRPDTA.F4981.FHUOM,
CRPDTA.F4981.FHCGC1;
答案 3 :(得分:0)
此查询将为您提供给定FHSHPN和FHCGC1的最大值为FHUK01的行。
with tab(FHUK01, FHSHPN, FHRTDQ, FHUOM, FHCGC1, RN) as
(select CRPDTA.F4981.FHUK01,
CRPDTA.F4981.FHSHPN,
CRPDTA.F4981.FHRTDQ,
CRPDTA.F4981.FHUOM,
CRPDTA.F4981.FHCGC1,
row_number() over (partition by crpdta.f4981.FHSHPN, CRPDTA.F4981.FHCGC1 order by CRPDTA.F4981.FHUK01 desc) rn
from CRPDTA.f4981
where crpdta.f4981.FHSHPN=4577085
AND CRPDTA.F4981.FHCGC1 = 'DIS')
select FHUK01, FHSHPN, FHRTDQ, FHUOM, FHCGC1
from tab
where rn = 1;
答案 4 :(得分:0)
我原来的帖子只是我试图构建的合并查询的内部部分。我最终使用San的建议让它工作......
MERGE INTO CRPDTA.F4941 DST
USING (WITH TAB (RSSHPN,RSRSSN,RSDSTN,RSUMD1,RSADDJ,FHUK01,FHSHPN,FHRTDQ,FHUOM,FHCGC1,RN) AS
(SELECT CRPDTA.F4941.RSSHPN,
CRPDTA.F4941.RSRSSN,
CRPDTA.F4941.RSDSTN,
CRPDTA.F4941.RSUMD1,
CRPDTA.F4941.RSADDJ,
CRPDTA.F4981.FHUK01,
CRPDTA.F4981.FHSHPN,
CRPDTA.F4981.FHRTDQ,
CRPDTA.F4981.FHUOM,
CRPDTA.F4981.FHCGC1,
ROW_NUMBER() OVER (PARTITION BY CRPDTA.F4941.RSSHPN, CRPDTA.F4941.RSRSSN, CRPDTA.F4981.FHSHPN, CRPDTA.F4981.FHCGC1 ORDER BY CRPDTA.F4981.FHUK01 DESC) RN
FROM CRPDTA.F4941
INNER JOIN CRPDTA.F4981
ON CRPDTA.F4941.RSSHPN = CRPDTA.F4981.FHSHPN
WHERE CRPDTA.F4941.RSDSTN = 0
AND CRPDTA.F4941.RSADDJ > 110365
AND CRPDTA.F4981.FHCGC1 = 'DIS')
SELECT * FROM TAB
WHERE RN = 1) SRC
ON (DST.RSSHPN = SRC.FHSHPN)
WHEN MATCHED THEN UPDATE
SET DST.RSDSTN = ROUND(SRC.FHRTDQ/10000,0), DST.RSUMD1 = SRC.FHUOM;