DB2 Query多重选择和按日期求和

时间:2018-05-18 16:10:26

标签: db2

我有3张桌子:ITEMS,ODETAILS,OHIST。

  • ITEMS - 产品列表,ID是关键字段
  • ODETAILS - 每个订单的订单项,无关键字段
  • OHIST - 按月显示去年订单总数的视图
ITEMS             ODETAILS                                 OHIST
+----+----------+  +-----+---------+---------+----------+  +---------+-------+
| ID |   NAME   |  | OID |  ODUE   | ITEM_ID | ITEM_QTY |  | ITEM_ID | M5QTY |
+----+----------+  +-----+---------+---------+----------+  +---------+-------+
| 10 + Widget10 |  | A33 | 1180503 |    10   |    100   |  |    10   |  1000 |
+----+----------+  +-----+---------+---------+----------+  +---------+-------+
| 11 + Widget11 |  | A33 | 1180504 |    11   |    215   |  |    11   |  1500 |
+----+----------+  +-----+---------+---------+----------+  +---------+-------+
| 12 + Widget12 |  | A34 | 1180505 |    10   |    500   |  |    12   |  2251 |
+----+----------+  +-----+---------+---------+----------+  +---------+-------+
| 13 + Widget13 |  | A34 | 1180504 |    11   |    320   |  |    13   |  4334 |
+----+----------+  +-----+---------+---------+----------+  +---------+-------+
                   | A34 | 1180504 |    12   |    450   |
                   +-----+---------+---------+----------+
                   | A34 | 1180505 |    13   |    125   |
                   +-----+---------+---------+----------+

假设今天是2018年5月2日(1180502) 我希望我的结果显示按天分组的ID,NAME,M5QTY和SUM(ITEM_QTY) 在接下来的3天内(D1,D2,D3)

Desired Result
+----+----------+--------+------+------+------+
| ID |   NAME   | M5QTY  |  D1  |  D2  |  D3  |
+----+----------+--------+------+------+------+
| 10 | Widget10 |  1000  |  100 |      |  500 |
+----+----------+--------+------+------+------+
| 11 | Widget11 |  1500  |      |  535 |      |
+----+----------+--------+------+------+------+
| 12 | Widget12 |  2251  |      |  450 |      |
+----+----------+--------+------+------+------+
| 13 | Widget13 |  4334  |      |      |  125 |
+----+----------+--------+------+------+------+

这是我将ODUE转换为日期的方式

DATE(concat(concat(concat(substr(char((ODETAILS.ODUE-1000000)+20000000),1,4),'-'), concat(substr(char((ODETAILS.ODUE-1000000)+20000000),5,2), '-')), substr(char((ODETAILS.ODUE-1000000)+20000000),7,2)))

1 个答案:

答案 0 :(得分:0)

试试这个(你可以添加你需要的连接)

SELECT  ITEM_ID
,     SUM(CASE WHEN ODUE = INT(CURRENT DATE) - 19000000 + 1 THEN ITEM_QTY ELSE 0 END) AS D1
,     SUM(CASE WHEN ODUE = INT(CURRENT DATE) - 19000000 + 2 THEN ITEM_QTY ELSE 0 END) AS D2
,     SUM(CASE WHEN ODUE = INT(CURRENT DATE) - 19000000 + 3 THEN ITEM_QTY ELSE 0 END) AS D3
FROM
    ODETAILS
GROUP BY
    ITEM_ID