同一表中的总和与减列

时间:2019-01-29 16:22:00

标签: sql ms-access

我有下表“ TableOfDelivery”,其中有4列

enter image description here

我已经计算出一个SQL查询(2016年访问权限),以获取 2 个不同报告周的 2 个交付周之间的差异:

SELECT TOP 2 
 t1.ref, t1.[delivery week], 
 (t2.qty-t1.qty) AS 
QtyDifferenceBetween2DeliveryWeekOn2DifferentWeekReporting
FROM 
  TableOfDelivery AS t1 INNER JOIN TableOfDelivery AS t2 ON (t1.ref = t2.ref) 
AND 
  (t1.[delivery week] = t2.[delivery week]  AND (t1.[reporting week] <> t2. 
[reporting week]) )
GROUP BY t1.[reporting week], t1.ref, t1.[delivery week], t2.qty-t1.qty
ORDER BY t1.[reporting week];

这是该SQL查询的结果:

enter image description here

仅在匹配的交付周内结果是好的。但是我也希望交货周数不匹配,请查看图中以红色和绿色突出显示的行。

enter image description here

例如,对于红线和绿线,我也应该在结果查询中使用

enter image description here

有什么可以做的吗?

非常感谢您

2 个答案:

答案 0 :(得分:0)

当我旋转以上数据时,它看起来像这样。您需要什么样的结果。请给我们看看。

            Deliv.Week-->               
Rptg.Week V                 
Sum of  qty Column Labels               
Row Labels  2019-35 2019-41 2019-43 2019-45 Grand Total
2018-37     20      30      50      30      130
2018-41     30                      30      60
Grand Total 50      30      50      60      190

答案 1 :(得分:0)

您可以尝试使用CASE来获取想要的东西。

SELECT t1.ref,
       t1.[delivery week],
       (t2.qty-t1.qty) AS QtyDiff,
       t1.[delivery week],
       CASE
           WHEN t1.[reporting week] <> t1.[delivery week] THEN t1.qty *-1
           ELSE t1.qty
       END AS new_qty
FROM TableOfDelivery AS t1
INNER JOIN TableOfDelivery AS t2 ON (t1.ref = t2.ref)
AND (t1.[delivery week] = t2.[delivery week]
     AND (t1.[reporting week] <> t2. [reporting week]))
GROUP BY t1.[reporting week],
         t1.ref,
         t1.[delivery week], (t2.qty-t1.qty),t1.qty
ORDER BY t1.[reporting week];

CASE检查交货周和报告周之间是否有差异。如果是这样,它将给您数量* -1。

我测试过它的Postgres,但不是作为MSACCESS我没有在我的电脑这个分贝。