1

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

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

我需要这个查询来调整树形小漫画商店。在我上次的任务之后,我在这里得到了很好的帮助,以便我获得所有树店的真实库存单位。但是任何将这个结果与销售表结合起来的尝试都会让我回到库存单位的两个错误计算上。

这是桌子的图片:

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

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

4

1 回答 1

0

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

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 

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

于 2018-06-19T10:18:52.837 回答