所以我运行了这个小查询,我似乎有些奇怪的事情发生了。
我想显示库存大于库存平均库存的所有商品(如果有意义的话......)。
当我运行它时,其中一个产品的库存少于计算的平均值......我不知道为什么。在这种情况下,不应该返回的项目是:421
返回数据:
"sum(quantity_stocked)" "count(product_id)" "avg(quantity_stocked)"
"15885" "18" "882.5000"
"product_id" "quantity_stocked"
"861" "1082"
"591" "1948"
"485" "1402"
"421" "858"
"277" "1920"
"214" "902"
"59" "1021"
查询:
select sum(quantity_stocked), count(product_id), avg(quantity_stocked)
FROM products;
SELECT product_id, quantity_stocked
FROM products
WHERE quantity_stocked > (
SELECT avg(quantity_stocked)
FROM products
GROUP BY product_id
LIMIT 1
);
剩余代码:
CREATE TABLE products
(
product_ID int(10) UNIQUE,
product_name varchar(30) NOT NULL,
quantity_stocked int(5),
product_cost dec(8,2) NOT NULL,
PRIMARY KEY (product_ID)
);
INSERT INTO products VALUES
(452,'Nike SS Pro Top',418, 22.99),
(861,'Nike LunarGlide 7',1082, 74.99),
(453,'Nike LS Pro Top',654, 64.99),
(454,'Nike SS Pro Top',720, 64.99),
(451,'Nike Pro Tank',480, 45.99),
(485,'Nike 5k Run Short',1402, 24.99),
(582,'Nike Fit Capri',750, 29.99),
(591,'Nike Be Fast Tight',1948, 39.99),
(847,'Nike Legend Tee',120, 34.99),
(277,'Nike Miller v-neck',1920, 44.99),
(135,'Adidas Soccer Pant',630, 34.99),
(456,'Adidas SS Breathe Top',754, 19.99),
(457,'Adidas Pro Cleat',626, 44.99),
(214,'Adidas Slide',902, 19.99),
(054,'Underarmor SL Top',854,54.99),
(059,'Undersarmor LS High Neck',1021,54.99),
(574,'Underarmor TR Short',746,24.99),
(421,'Underarmor TR Balance Shoe',858,84.99);
答案 0 :(得分:2)
在您的子查询中,您与产品的一个的平均值进行比较(在此特定示例中,将为#452,其中quantity_stocked
为418),而非平均值所有产品。只需删除此部分:
GROUP BY product_id
LIMIT 1