我正在研究简单的查询来学习MySQL,在我的示例数据库中,我跟踪销售电子设备的商店,我有一张桌子卖(商店,物品,价格)。
示例数据是,
'Best Buy', 'Galaxy S', 1000
'Buy More', 'Macbook Air', 2000
'Best Buy', 'Microsoft Mouse', 20
'Best Buy', 'Macbook Pro Cover', 40
'Buy More', 'Asus Zenbook', 2000
等等..
我尝试了以下sql语句,但它说:
错误代码:1111。无效使用组功能0.000秒
SELECT store
FROM sells
WHERE SUM(price) <
(SELECT SUM(price) AS total
FROM sells
GROUP BY store
ORDER BY total DESC
LIMIT 1)
GROUP BY store
ORDER BY SUM(price) DESC
如果你能帮助我,我将不胜感激
由于
答案 0 :(得分:4)
这只会显示第二个最贵的商店;
SELECT STORE
FROM TABLE_A
GROUP BY STORE
ORDER BY SUM(PRICE) DESC
LIMIT 1,1
演示here。
如果您想要显示价格,您也可以选择它;
SELECT STORE, SUM(PRICE) TOTAL_PRICE
FROM TABLE_A
GROUP BY STORE
ORDER BY TOTAL_PRICE DESC
LIMIT 1,1
演示here。
编辑:如果你有几个最昂贵的商店和几个第二昂贵的商店,那么获得所有第二个最昂贵商店的查询变得相当复杂;我相信有人可以击败这个效率;
SELECT STORE, SUM(PRICE) TOTAL_PRICE
FROM TABLE_A
GROUP BY STORE
HAVING TOTAL_PRICE =
(SELECT SUM(PRICE) TMP
FROM TABLE_A
GROUP BY STORE
HAVING TMP <
(SELECT SUM(PRICE) TMP2
FROM TABLE_A
GROUP BY STORE
ORDER BY TMP2 DESC
LIMIT 1)
ORDER BY TMP DESC LIMIT 1)
演示here。
答案 1 :(得分:1)
你可以这样做;
SELECT *,
SUM(price) AS totalprice
FROM sells
GROUP BY store
ORDER BY totalprice DESC
LIMIT 2
首先选择价格总和并将其临时存储在ex。总价格,然后你已经逐个商店。要获得最昂贵的商店,请向后订购金额,然后将结果限制为两个。
当您循环结果时,您将能够将总价格作为普通列
答案 2 :(得分:1)
几乎正确,
SELECT SUM(price) as price_total FROM sells GROUP BY store
如果你想订购你可以做子查询,比如:
SELECT price_total FROM (SELECT SUM(price) as price_total FROM sells GROUP BY store) as res ORDER BY price LIMIT 2
如果您想获得第二名,您可能会进行另一次查询,但我认为最好使用您的后端语言
答案 3 :(得分:0)
SELECT distinct price from sells ORDER BY price DESC
,在您的代码中,只需选择第二个。
如果您需要其余信息,请执行以下操作:
SELECT * from sells
WHERE price = (SELECT distinct price from sells ORDER BY price DESC LIMIT 1,1)
答案 4 :(得分:0)
没有测试它但应该工作
SELECT S.store
FROM (
SELECT SUM(T.price) AS sum_price
FROM formList_Total AS T
GROUP BY T.store
) AS S
ORDER BY sum_price DESC
LIMIT 1 , 1
对不起,去了测试,这是我最终的结果。