1

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

Shop    |    Date   | Item

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

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

因此,商品 A(售出 3 件)占总数(售出 5 件)的 60%,商品 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

4 回答 4

1

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

于 2013-06-09T13:45:25.900 回答
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

于 2013-06-09T10:16:44.190 回答
0

你可以试试这个:

SELECT DISTINCT( A.SHOP ) ,A.ITEM ,COUNT(A.ITEM) 项目 ,CAST(COUNT(A.item) * 100 / B.COUNT_OF_SHOP AS VARCHAR(10)) + '%'
FROM 百分比 A JOIN
( SELECT shop ,COUNT(shop) AS COUNT_OF_SHOP FROM percent GROUP BY shop ) B ON A.shop = B.shop
GROUP BY A.Shop ,B.shop ,A.item ,B.COUNT_OF_SHOP
于 2013-06-09T11:48:03.463 回答
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

于 2013-06-09T09:11:06.493 回答