连接两个 tables 而没有计算错误的输出或在 table 中缺少带有 NULL 的输出

Joining two tables without miscalculated output or missing output with a NULL in table

第一个 table 调用 stockcurrent 并包含来自不同商店的所有产品项目。第二个 table 包含树店的所有销售额。现在我想加入这两个 tables 并得到一个输出,我在每个销售中找到每个商店的正确库存,它应该看起来像下面的 table

销售项目 store_1_stock store_2_stock store_3_stock 但我总是有两个问题: 首先: 如果某件商品从未出现在其中一家树店中 它没有出现在列表中 第二个: 如果在给定的时间范围内售出不止一件商品,它会翻倍 或将库存单位的产量增加三倍

我需要这个查询来调整 tree 小漫画店。 在我上次查询之后,我得到了很好的帮助,这样我就可以获得所有树木商店的实际库存单位。但是任何尝试将此结果与销售额结合起来 table 都会让我想起库存单位的两个错误计算。

这是 table 的照片:

https://www.dropbox.com/preview/stockcurrent_table.PNG?role=personal

https://www.dropbox.com/preview/ticketlines_table.PNG?role=personal

SELECT 
products.name AS VK_Artikel,
SUM(CASE WHEN stockcurrent.location ='100' 
    THEN stockcurrent.units ELSE 0  END) AS Versand_Bestand,
SUM(CASE WHEN stockcurrent.location ='3b53adf5-eaee-4a13-b22b-39d50b14e497' 
    THEN stockcurrent.units ELSE 0 END) AS K_Strasse,
SUM(CASE WHEN stockcurrent.location ='a59cb899-27f4-460c-b5df-89a89eaaef75' 
    THEN stockcurrent.units ELSE 0 END) AS O_Strasse,
SUM(CASE WHEN stockcurrent.location =  '0' 
    THEN stockcurrent.units ELSE 0 END) AS EU
FROM ticketlines
  JOIN products
ON ticketlines.product = products.id
  JOIN tickets
ON ticketlines.ticket = tickets.id
  JOIN receipts 
ON tickets.id = receipts.id
  JOIN closedcash
ON receipts.money = closedcash.money
  JOIN stockcurrent
ON stockcurrent.product = products.id
  WHERE closedcash.host ='X_Online'
    AND closedcash.datestart > $P{startzeit}
Group BY VK_Artikel ASC    

我希望得到以下输出:

Sold Item  store_1_Stock store_2_Stock store_3_Stock
 comic 1         1              2            1

号码来自各店铺

如果该商品售出不止一次,我会知道

Sold Item  store_1_Stock store_2_Stock store_3_Stock
 comic 1         3              6            3

或者如果一件商品在其中一家商店出售但从未在所有树木商店中出售,它永远不会给出输出。

为避免计算错误,我建议您在单独的子句中进行计算,然后将其与主查询结合起来。

SELECT 
    p.name AS VK_Artikel,
    s.Versand_Bestand,
    s.K_Strasse,
    s.O_Strasse,
    s.EU
FROM ticketlines tl
  JOIN products p
ON tl.product = p.id
  JOIN tickets t
ON tl.ticket = t.id
  JOIN receipts r
ON t.id = r.id
  JOIN closedcash c
ON r.money = c.money
 LEFT JOIN (
  SELECT product
    SUM(CASE WHEN location ='100' THEN units ELSE 0  END) AS Versand_Bestand,
    SUM(CASE WHEN location ='3b53adf5-eaee-4a13-b22b-39d50b14e497' THEN units ELSE 0 END) AS K_Strasse,
    SUM(CASE WHEN location ='a59cb899-27f4-460c-b5df-89a89eaaef75' THEN units ELSE 0 END) AS O_Strasse,
    SUM(CASE WHEN location =  '0' THEN units ELSE 0 END) AS EU
    FROM stockcurrent
    GROUP BY product
  ) s
ON s.product = p.id
  WHERE c.host ='X_Online'
    AND c.datestart > $P{startzeit}
ORDER BY VK_Artikel ASC 

查询中涉及的联接可能有很多行针对影响您的数字的每个产品,此外,如果您仍然有重复的行,您可以在 select 子句中添加 distinct SELECT DISTINCT ....