我有一個查詢可以給出最近三個月的銷售額。我想在一個查詢中獲得所有三個月的數據,而不是三個不同的查詢。如果我給予'2016年3月',它應該顯示我最近三個月的數據2016年2月,2016年1月和2015年12月。如何在單個查詢中獲取最近三個月的數據
請幫我這個。
SELECT
TO_CHAR(A.JOB_DATE , 'MON-YYYY') S_MON , NULL T_MON,
TO_CHAR(A.JOB_DATE,'MM-YYYY') MM, C.SECTION_CODE SECTION,
B.ITEM_CODE ITEM_CODE, SUM(B.MASTER_QUANTITY) SALES,
NULL TARGET
FROM
TRANSACTION_MASTER A, TRANSACTION_DETAIL B,
ITEM_SECTION C, ITEM D
WHERE
A.TRANSACTION_NUMBER = B.TRANSACTION_NUMBER
AND TO_CHAR(ADD_MONTHS(A.JOB_DATE,1), 'MON-YYYY') = 'MAR-2016'
AND A.TRANSACTION_CODE = B.TRANSACTION_CODE
AND B.ITEM_CODE = D.ITEM_CODE
AND C.SECTION_CODE = D.SECTION_CODE
AND A.TRANSACTION_CODE IN (2,4)
AND D.ITEM_STATUS = 'A'
AND C.SECTION_CODE BETWEEN :ST_CODE AND :END_CODE
GROUP BY
TO_CHAR(A.JOB_DATE, 'MON-YYYY'), TO_CHAR(A.JOB_DATE, 'MM-YYYY'),
C.SECTION_CODE, B.ITEM_CODE
UNION
SELECT
TO_CHAR(A.JOB_DATE, 'MON-YYYY') S_MON, NULL T_MON,
TO_CHAR(A.JOB_DATE, 'MM-YYYY') MM,
C.SECTION_CODE SECTION, B.ITEM_CODE ITEM_CODE,
SUM(B.MASTER_QUANTITY) SALES, NULL TARGET
FROM
TRANSACTION_MASTER A, TRANSACTION_DETAIL B,
ITEM_SECTION C, ITEM D
WHERE
A.TRANSACTION_NUMBER = B.TRANSACTION_NUMBER
AND TO_CHAR(ADD_MONTHS(A.JOB_DATE, 2), 'MON-YYYY')= 'MAR-2016'
AND A.TRANSACTION_CODE = B.TRANSACTION_CODE
AND B.ITEM_CODE = D.ITEM_CODE
AND C.SECTION_CODE = D.SECTION_CODE
AND A.TRANSACTION_CODE IN (2,4)
AND D.ITEM_STATUS = 'A'
AND C.SECTION_CODE BETWEEN :ST_CODE AND :END_CODE
GROUP BY TO_CHAR(A.JOB_DATE , 'MON-YYYY') , TO_CHAR(A.JOB_DATE,'MM-YYYY') ,C.SECTION_CODE , B.ITEM_CODE
UNION
SELECT TO_CHAR(A.JOB_DATE , 'MON-YYYY') S_MON , NULL T_MON , TO_CHAR(A.JOB_DATE,'MM-YYYY') MM ,
C.SECTION_CODE SECTION , B.ITEM_CODE ITEM_CODE , SUM(B.MASTER_QUANTITY) SALES , NULL TARGET
FROM TRANSACTION_MASTER A , TRANSACTION_DETAIL B , ITEM_SECTION C , ITEM D
WHERE A.TRANSACTION_NUMBER = B.TRANSACTION_NUMBER
AND TO_CHAR(ADD_MONTHS(A.JOB_DATE,3),'MON-YYYY') = 'MAR-2016'
AND A.TRANSACTION_CODE = B.TRANSACTION_CODE
AND B.ITEM_CODE = D.ITEM_CODE
AND C.SECTION_CODE = D.SECTION_CODE
AND A.TRANSACTION_CODE IN (2,4)
AND D.ITEM_STATUS = 'A'
AND C.SECTION_CODE BETWEEN :ST_CODE AND :END_CODE
GROUP BY TO_CHAR(A.JOB_DATE , 'MON-YYYY') , TO_CHAR(A.JOB_DATE,'MM-YYYY') ,C.SECTION_CODE , B.ITEM_CODE
[不良習慣踢:使用舊式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style- joins.aspx) - 在ANSI - ** 92 ** SQL標準中**舊式*逗號分隔的表*樣式列表已替換爲* proper * ANSI'JOIN'語法(**超過20年**之前),其使用是不鼓勵 –