SQL返回值占子类别的百分比
我有一个查询:(使用一个非常简单的示例)
SELECT
ItemCategory,
ItemID,
Sales
FROM
MyTable
WHERE
CustomerID = 1
它返回
ItemCategory | ItemID | Sales
A 0 75.00
A 1 50.00
A 2 0.00
B 3 25.00
B 4 25.00
C 5 20.00
C 6 30.00
C 7 10.00
C 8 0.00
C 9 50.00
如何修改此查询以便收到按 ItemCategory 分组的每个商品的销售百分比?
也就是说,我希望返回这个:
ItemCategory | ItemID | Sales | PercentageOfCategory
A 0 75.00 60%
A 1 50.00 40%
A 2 0.00 0%
B 3 25.00 50%
B 4 25.00 50%
C 5 20.00 20%
C 6 30.00 30%
C 7 10.00 10%
C 8 0.00 0%
C 9 50.00 50%
我试图使示例尽可能简单,实际查询非常复杂,但我想相同的逻辑仍然适用。
编辑:我相信服务器是 sql server 2008
I have a query: (using a very simple example)
SELECT
ItemCategory,
ItemID,
Sales
FROM
MyTable
WHERE
CustomerID = 1
Which returns
ItemCategory | ItemID | Sales
A 0 75.00
A 1 50.00
A 2 0.00
B 3 25.00
B 4 25.00
C 5 20.00
C 6 30.00
C 7 10.00
C 8 0.00
C 9 50.00
How can I modify this query so that I receive the percentage of sales for each item grouped by ItemCategory?
That is, I would like this returned:
ItemCategory | ItemID | Sales | PercentageOfCategory
A 0 75.00 60%
A 1 50.00 40%
A 2 0.00 0%
B 3 25.00 50%
B 4 25.00 50%
C 5 20.00 20%
C 6 30.00 30%
C 7 10.00 10%
C 8 0.00 0%
C 9 50.00 50%
I tried to keep the example as trivial as possible, the actual query is pretty complex but I imagine the same logic still applies.
EDIT: I believe the server is sql server 2008
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有提到 SQL Server 的版本,但如果您有 2005+,那么您可以使用 通用表表达式 (CTE)
You did not mention what version of SQL server but if you have 2005+ then you could use Common Table Expressions (CTE)
假设 CTE 使用 SQL Server 2005+:
Assuming SQL Server 2005+ for the CTE:
您可以使用
SUM ... OVER
You can use
SUM ... OVER