0

我希望能够编写一个 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
4

5 回答 5

2

要获得计数,请使用CASEfor HighPriceCount,如下所示。聚合函数不计算在内null,除了COUNT(*)

Sql-Fiddle 示例

SELECT Product, COUNT(*) as Total, 
       COUNT(case when price > 10 then 1 end) as HighPriceCount,
       SUM(case when price > 10 then price end)/COUNT(*) as Avg
FROM Orders 
WHERE Location = 'Amazon'
GROUP BY Product
于 2013-03-06T19:01:42.380 回答
1

您是否尝试使用 SUM 和 CASE?(不能正确尝试知道我认为它应该有效)

SELECT PRODUCT,
       SUM(CASE WHEN PRICE>10 THEN 1 ELSE 0 END) as highpricecount,
       COUNT(CASE WHEN PRICE>10 THEN 1 END) as total
FROM Orders 
WHERE LOCATION='AMAZON'
GROUP BY PRODUCT;
于 2013-03-06T19:02:20.150 回答
0

这是我的...

Select  Product, Total, HighPriceCount, HighPriceCount/Total As Avg
From   (Select  Product,
                Sum(Case When Location = 'Amazon' Then 1 Else 0 End) As Total,
                Sum(Case When Location = 'Amazon' And Price > 10 Then 1 Else 0 End) As HighPriceCount,
        From    Orders
        Group   By Product) o
于 2013-03-06T19:05:01.547 回答
0

这是我的

Select 
Product, Sum(Total) as Total, Sum(HighPriceCount) as HighPriceCount,Total/HighPriceCount as AVG
from 
(
select Product, 1 as Total, case WHEN PRICE>10 THEN 1 ELSE 0 END as HighPriceCount
from Orders where LOCATION='AMAZON'
) 
group by Product
于 2013-03-06T19:14:40.710 回答
0

您的查询不起作用。请试试这个:

select A.Product, A.Total, ISNULL(B.HighPriceCount,0), B.HighPriceCount*1.0/A.Total*1.0 as [Avg]
(select Product, count(*) as Total
from Orders 
where Location='Amazon'
group by Product ) A
left join 
(SELECT Product, COUNT(*) as HighPriceCount 
from Orders 
where Location = 'Amazon' and Price > 10
group by Product) B
on A.Product = B.Product

我没有你的数据库,所以可能有错字,我无法测试这个查询,但是你做了一些改变,它应该可以工作。

于 2013-03-06T19:30:40.103 回答