我希望能够编写一个 SQL 查询,该查询可以COUNT
根据不同的条件使用多个 s 并将值组合在一起。
假设我有一个(固定的)场景,我改变了我的产品的价格点,并想分析人们支付了什么。
SELECT Product, COUNT(*) as Total FROM Orders WHERE Location = 'Amazon'
SELECT Product, COUNT(*) as HighPriceCount FROM Orders
WHERE Location = 'Amazon' and PRICE > 10
从这里,我希望能够看到这样的结果。
--------------------------------------------
| Product | Total | HighPriceCount | Avg |
--------------------------------------------
| Game 1 | 50 | 20 | .40 |
| Prod 2 | 300 | 200 | .66 |
--------------------------------------------
平均位置 是“10 以上的价格”/“总售出”。我最初的方法是分组,Product
但我想看看“内部选择”是否是唯一的路径,或者是否有更优雅的方式来做到这一点。好像有很多重复?这是我最初的查询版本。
-- I don't know if this works?
SELECT Product, COUNT(*) AS Total,
(
SELECT Product, COUNT(*) FROM Orders WHERE Location = 'Amazon' and Price > 10
GROUP BY Product
) AS HighPriceCount,
(Total / HighPriceCount) AS Avg
From Orders
WHERE Location = 'Amazon'
GROUP BY Product