我有一个SQL查询,它为多个发票编号和发票行项目返回多行,但我只希望记录中每个发票的最新日期+行项目组合。我试过这个,但显然MAX Date是不可能的!
SELECT *
FROM (
SELECT
CD.NAME,
DSF.SALES_DOC, -- EACH SALES_DOC COULD HAVE MULTIPLE LINE ITEMS
DSF.LINE_ITEM,
MD.MATERIAL_DESC,
TO_DATE(MMF.RECEIVED_DATE_KEY,'YYYYMMDD') AS RECDATE -- EACH
SALESDOC/LINE COULD HAVE MULTIPLE DATES
FROM
MART.DAILYSALES DSF,
MART.MARKET MMF,
MART.MATERIAL MD,
MART.LINESTATUS ALS,
MART.CUSTOMER CD
WHERE
DSF.SALES_DOC = MMF.SALES_DOC
AND DSF.LINE_ITEM = MMF.LINE_ITEM
AND DSF.MATERIAL_ID = MD.MATERIAL_ID
AND ALS.LINE_STATUS = MMF.LINE_STATUS
AND CD.SOLDCUSTOMER = DSF.SOLDCUSTOMER_KEY
AND TO_DATE(MMF.RECEIVED_DATE_KEY,'YYYYMMDD') >
TO_DATE('20170601','YYYYMMDD')
)
WHERE
MAX ( TO_DATE(MMF.RECEIVED_DATE_KEY,'YYYYMMDD'))
GAV INC 100001 01 WIDGETS 20170101
GAV INC 100001 01 WIDGETS 20170501
GAV INC 100001 01 WIDGETS 20170801 - Want this line only as latest date
GAV INC 100001 02 WIDGETS 20170101
GAV INC 100001 02 WIDGETS 20170501 - Want this line only as latest date
GAV INC 100002 01 WIDGETS 20170301
GAV INC 100002 01 WIDGETS 20170501
GAV INC 100002 01 WIDGETS 20170901 - Want this line only as latest date
答案 0 :(得分:1)
您可以使用GROUP BY NAME, SALES_DOC, LINE_ITEM, MATERIAL_DESC
。
SELECT
NAME,
SALES_DOC,
LINE_ITEM,
MATERIAL_DESC,
MAX(TO_DATE(RECEIVED_DATE_KEY,'YYYYMMDD')) AS RECDATE
FROM
DAILYSALES
JOIN MARKET USING(SALES_DOC)
JOIN MATERIAL USING(MATERIAL_ID)
JOIN LINESTATUS USING(LINE_STATUS)
JOIN CUSTOMER USING(SOLDCUSTOMER_KEY)
WHERE
TO_DATE(RECEIVED_DATE_KEY,'YYYYMMDD') > TO_DATE('20170601','YYYYMMDD')
GROUP BY
NAME, SALES_DOC, LINE_ITEM, MATERIAL_DESC;
如果这不起作用,您可以使用ROW_NUMBER()
:
SELECT
NAME,
SALES_DOC,
LINE_ITEM,
MATERIAL_DESC,
RECDATE
FROM (
SELECT
NAME,
SALES_DOC,
LINE_ITEM,
MATERIAL_DESC,
MAX(TO_DATE(RECEIVED_DATE_KEY,'YYYYMMDD')) AS RECDATE,
ROW_NUMBER() OVER (PARTITION BY SALES_DOC, LINE_ITEM
ORDER BY RECEIVED_DATE_KEY DESC) AS RN
FROM
DAILYSALES
JOIN MARKET USING(SALES_DOC)
JOIN MATERIAL USING(MATERIAL_ID)
JOIN LINESTATUS USING(LINE_STATUS)
JOIN CUSTOMER USING(SOLDCUSTOMER_KEY)
WHERE
TO_DATE(RECEIVED_DATE_KEY,'YYYYMMDD') > TO_DATE('20170601','YYYYMMDD')) t
WHERE RN = 1;