我想写一个SQL查询,搜索商店的库存,那里出售的可口可乐比百事可乐多,这是我目前的查询和结果:
SELECT Verkoop.item_id, Verkoop.item_name, Verkoop.shop_name, SUM(Verkoop.sold) as WinkelTot
FROM(
SELECT tbl_items.item_id, tbl_items.item_name, shop_name, sold
FROM tbl_stock
NATURAL JOIN tbl_shops
NaTURAL JOIN tbl_items
ORDER BY sold DESC) AS Verkoop
WHERE Verkoop.item_name LIKE "%Coca Cola%" OR Verkoop.item_name LIKE "%Pepsi%"
GROUP BY
CASE
WHEN Verkoop.item_name LIKE "%Coca Cola%" THEN 'Coca Cola'
WHEN Verkoop.item_name LIKE "%Pepsi%" THEN 'Pepsi'
END,
Verkoop.shop_name
ORDER BY shop_name DESC
当前结果:
item_id i tem_name shop_name shop_sold
41 Pepsi Cola 6X1.5L TREKK Zaventem 566
40 Coca Cola 6X0.5L TREKK Zaventem 1662
41 Pepsi Cola 6X1.5L TREKK VLBR2 1292
40 Coca Cola 6X0.5L TREKK VLBR2 1478
39 Coca Cola 6X1.5L TREKK Landen 630
41 Pepsi Cola 6X1.5L TREKK Landen 1402
42 Pepsi Cola 6X0.5L TREKK Hola 1672
40 Coca Cola 6X0.5L TREKK Hola 862
42 Pepsi Cola 6X0.5L TREKk Antwerpen3 874
40 Coca Cola 6X0.5L TREKk Antwerpen3 895
39 Coca Cola 6X1.5L TREKk Antwerpen2 390
42 Pepsi Cola 6X0.5L TREKk Antwerpen2 1230
因此,此查询将返回所有百事可乐和可乐文章及其相应的商店和销售。
现在我想将每一行与他们的百事可乐变体进行比较。
需要的结果:
shop_name more_cola_than_pepsi
TREKK Zaventem yes
TREKK VLBR3 yes
TREKK LANDEN no
TREKK Hola no
TREKK Antwerpen3 yes
TREKK Antwerpen2 no
任何人都可能知道如何解决这个问题? 感谢。
答案 0 :(得分:1)
首先,不使用NATURAL JOIN
。它完全被打破了。它基于具有相同名称的列连接表,因此对任一表的定义进行小的更改可能会破坏查询。它甚至忽略了显式的外键引用。
其次,您在子查询中使用ORDER BY
。这是另一种危险的做法,在这种情况下,完全是多余的。
您想要的查询只能使用条件聚合:
SELECT sh.shop_name,
SUM(CASE WHEN i.item_name LIKE '%Coca Cola%' THEN st.sold ELSE 0 END) as Coke,
SUM(CASE WHEN i.item_name LIKE '%Pepsi%' THEN st.sold ELSE 0 END) as Pepsi,
(CASE WHEN SUM(CASE WHEN i.item_name LIKE '%Coca Cola%' THEN st.sold ELSE 0 END) >
SUM(CASE WHEN i.item_name LIKE '%Pepsi%' THEN st.sold ELSE 0 END)
THEN 'yes' ELSE 'no'
END) as CokeMoreThanPepsi
FROM tbl_stock st JOIN
tbl_shops sh
USING (<appropriate columns here>)
tbl_items i
USING (<appropriate columns here>)
WHERE i.item_name LIKE '%Coca Cola%' OR i.item_name LIKE '%Pepsi%'
GROUP BY sh.shop_name