多个GROUP BY?

时间:2013-03-06 18:54:57

标签: sql sql-server

我希望能够根据不同的标准编写一个可以使用多个COUNT的SQL查询,并将这些值组合在一起。

假设我有一个(罐装)场景,我可以更改产品的价格点,并想分析人们支付的费用。

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   | 
--------------------------------------------

Avg。是“价格高于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

5 个答案:

答案 0 :(得分:2)

要获得计数,请使用CASE HighPriceCount,如下所示。除null

外,汇总函数不计算COUNT(*)

Sql-Fiddle Example

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

答案 1 :(得分: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;

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分: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

我没有你的数据库,所以也许有拼写错误,我无法测试这个查询,但是你做了一些改动,它应该有效。