2017-10-20 121 views
0

最終,我想在AS/400(綠色屏幕)中將SQL數據按月份分組。GROUP BY將AS/400日期格式轉換爲SQL日期

這裏是最初的SQL查詢及其相應的結果:

SELECT ITNBRV, /* Item */ 
     ODDTRV, OQTYRV /* Order due due, Order quantity */ 
    FROM ORDREVLA /* MRP Recommendations */ 
WHERE ITNBRV = '17000' OR ITNBRV = '19000' /* Returns only items 17000, 19000 */ 

Query Result Screen Shot

我想利用這些數據和總結它像這樣:

Item number Order Due Date Order Quantity 
    17000   11/17   1296 
    17000   12/17   1296 
    17000   01/18   3564 
    17000   02/18   3888 
    19000   11/17   68100 
    19000   12/17   1800 
    19000   01/18   23220 

這是我用來轉換日期格式:

SELECT ITNBRV, 
     month(
     substr(ODDTRV,4,2) ||'/'|| 
     substr(ODDTRV,6,2) ||'/'|| 
     substr(ODDTRV,2,2)) ||'/'|| 
     year(
     substr(ODDTRV,4,2) ||'/'|| 
     substr(ODDTRV,6,2) ||'/'|| 
     substr(ODDTRV,2,2)) AS Month_Year, 
     OQTYRV 
    FROM ORDREVLA 
    WHERE ITNBRV = '17000' OR ITNBRV = '19000' 

結果如下:

Converted Dates

我試圖用GROUP BY以相同的轉化次數:

SELECT ITNBRV, 
     month(
     substr(ODDTRV,4,2) ||'/'|| 
     substr(ODDTRV,6,2) ||'/'|| 
     substr(ODDTRV,2,2)) ||'/'|| 
     year(
     substr(ODDTRV,4,2) ||'/'|| 
     substr(ODDTRV,6,2) ||'/'|| 
     substr(ODDTRV,2,2)) AS Month_Year, 
     OQTYRV 
    FROM ORDREVLA 
    WHERE ITNBRV = '17000' OR ITNBRV = '19000' 
GROUP BY (month(
     substr(ODDTRV,4,2) ||'/'|| 
     substr(ODDTRV,6,2) ||'/'|| 
     substr(ODDTRV,2,2))) 

但得到這個錯誤信息:

Column ITNBRV or expression in SELECT list not valid. 

謝謝!

回答

2

不熟悉AS/400 SQL,但看起來您需要按INTBRV進行分組併爲ORDREVLA添加聚合。

SELECT 
     ITNBRV, 
     month(
     substr(ODDTRV,4,2) ||'/'|| 
     substr(ODDTRV,6,2) ||'/'|| 
     substr(ODDTRV,2,2)) ||'/'|| 
     year(
     substr(ODDTRV,4,2) ||'/'|| 
     substr(ODDTRV,6,2) ||'/'|| 
     substr(ODDTRV,2,2)) AS Month_Year, 
     SUM(OQTYRV) as OQTYRV_Total 
FROM 
     ORDREVLA 
WHERE 
     ITNBRV = '17000' OR ITNBRV = '19000' 
GROUP BY (month(
      substr(ODDTRV,4,2) ||'/'|| 
      substr(ODDTRV,6,2) ||'/'|| 
      substr(ODDTRV,2,2))), 
      ITNBRV 
+0

DB2爲我,所以你有它正確的位置(AS/400 SQL)遵循SQL標準。這將是ISO/IEC 9075標準,第1-4,10,11和14部分.v7.2和v7.3支持2016標準,v7.1支持以前的標準。 – jmarkmurphy

+0

@jmarkmurphy:有些東西仍然關閉,現在我收到錯誤消息「列ODDTRV或SELECT列表中的表達式無效。」 – Sescopeland

+1

認爲你還需要組中的(年(...))表達式... – Charles

0

個人而言,我更喜歡用公用表表達式(CTE)來處理這個..

with mmyy as (
SELECT 
     ITNBRV, 
     month(
     substr(ODDTRV,4,2) ||'/'|| 
     substr(ODDTRV,6,2) ||'/'|| 
     substr(ODDTRV,2,2)) ||'/'|| 
     year(
     substr(ODDTRV,4,2) ||'/'|| 
     substr(ODDTRV,6,2) ||'/'|| 
     substr(ODDTRV,2,2)) AS Month_Year, 
     OQTYRV 
FROM 
     ORDREVLA 
WHERE 
     ITNBRV = '17000' OR ITNBRV = '19000' 
) 
select 
    itnbrv, month_year, sum(oqtyrv) as OQTYRV_Total 
from 
    mmyy 
group by 
    itnbrv, month_year