我对mySQL和phpMyAdmin比较陌生,我遇到的问题是我试图输入。我希望“售出的单位”是一个数字,但是整个列打印出“已售出的单位”某些原因。我已经尝试删除两个“售出单位”,我试图删除一个,但我不知道这里出了什么问题。对不起,如果我不够清楚,但这是我的疑问:
SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
FROM lgproduct
GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
ON b.brand_id = sub2.brand_id
ORDER BY brand_name;
这是一张与输出结果一致的图片:
答案 0 :(得分:2)
你非常接近:
SELECT
brand_name, brand_type,
round(avgprice,2) AS "Average Price", sub2.Units_Sold AS "Units Sold"
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
FROM lgproduct
GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
JOIN (SELECT brand_id, Sum(line_qty) AS Units_Sold
FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
ON b.brand_id = sub2.brand_id
ORDER BY brand_name;
答案 1 :(得分:1)
在mySQL中,您应该使用反引号`来表示列和表名。在这里,mySQL将“Units Sold”视为您身边的变量,这就是为什么在结果中将其打印出来的原因。
SELECT b.`brand_name`, b.`brand_type`, Round(sub1.`avgprice`, 2) AS "Average Price", sub2.`Units Sold`
FROM lgbrand b JOIN (SELECT `brand_id`, Avg(`prod_price`) AS avgprice
FROM lgproduct
GROUP BY `brand_id`) sub1
ON b.`brand_id` = sub1.`brand_id`
JOIN (SELECT `brand_id`, Sum(`line_qty`) AS "Units Sold"
FROM lgproduct p JOIN lgline l ON p.`prod_sku` = l.`prod_sku`
GROUP BY `brand_id`) sub2
ON b.`brand_id` = sub2.`brand_id`
ORDER BY `brand_name`;
答案 2 :(得分:0)
如果你想在你的名字中保留空格,请使用:
SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", `Units Sold`
FROM lgbrand b JOIN (SELECT brand_id, Avg(prod_price) AS avgprice
FROM lgproduct
GROUP BY brand_id) sub1
ON b.brand_id = sub1.brand_id
JOIN (SELECT brand_id, Sum(line_qty) AS "Units Sold"
FROM lgproduct p JOIN lgline l ON p.prod_sku = l.prod_sku
GROUP BY brand_id) sub2
ON b.brand_id = sub2.brand_id
ORDER BY brand_name;
在postgres和Oracle中你可以做" fieldname"在Mysql中使用