gpt4 book ai didi

mysql - SQL检查一行的值是否大于下一行

转载 作者:行者123 更新时间:2023-11-29 12:11:46 24 4
gpt4 key购买 nike

我想编写一个 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

有人知道如何解决这个问题吗?谢谢。

最佳答案

首先,不要使用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

关于mysql - SQL检查一行的值是否大于下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30545901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com