Sql百分比计算和分组

时间:2013-06-09 09:01:21

标签: sql

我有一张包含商店名称,销售日期和销售商品的表格:

Shop    |    Date   | Item

Shop1   |   xxxxx   | A
Shop1   |   xxxxx   | B
Shop1   |   xxxxx   | B
Shop1   |   xxxxx   | A
Shop1   |   xxxxx   | A

所以他们卖了3件'A'和2件'B'

因此,A项(已售出3件)占总数的60%(已售出5件)而B件为40%

所以我希望得到这样的东西:

Shop1   |   A    |  3    |  60%
Shop1   |   B    |  2    |  40%

应该通过以下方式获得:

Select Shop, item, count(item),  count(item) *100 / (select count(item)  from table) +  '%'
from table
group by Shop, item;

我的问题是这些桌子不仅包含一个商店,而是其他商店:shop1,shop2等等。

所以我想获得这样的结果:

Shop1   |   A    |  3    |  60%
Shop1   |   B    |  2    |  40%
Shop2   |   A    |  8    |  80%
Shop2   |   B    |  2    |  20%
shop3   |   A    |  1    |  100%
shop4……

任何帮助?

4 个答案:

答案 0 :(得分:1)

在SQLServer2005 +

SELECT shop, item,
       COUNT(*) * 100. / SUM(COUNT(*)) OVER(PARTITION BY shop) AS Perc
FROM dbo.YourTable
GROUP BY shop, item
ORDER BY shop, item

演示SQLFiddle

答案 1 :(得分:1)

我创建了一个包含20000个随机值的表格并测试了3个以上的答案,并发现Fedorenko的答案比benty23更快。  在查询计划中,0.250533用于Fedorenko,0.354073用于benty23。 因此,使用窗口函数来解决这个问题是最佳解决方案。

答案 2 :(得分:0)

以下内容应该有效:

Select i.Shop, 
       i.item, 
       count(i.item), (count(i.item) * 100 / t.cnt) 
  from table1 i
  join (select shop, count(shop) as cnt from table1 group by shop) t
    on i.shop = t.shop
 group by i.Shop, i.item, t.cnt

另见sqlfiddle

答案 3 :(得分:0)

你可以试试这个:

SELECT DISTINCT( A.SHOP ) ,A.ITEM ,COUNT(A.ITEM) ITEMS ,CAST(COUNT(A.item) * 100 / B.COUNT_OF_SHOP AS VARCHAR(10)) + '%'
FROM    percentage A JOIN 
( SELECT   shop ,COUNT(shop) AS COUNT_OF_SHOP FROM percentage GROUP BY shop ) B ON A.shop = B.shop
GROUP BY A.Shop ,B.shop ,A.item ,B.COUNT_OF_SHOP