如何计算该行的值与行之和的除法

时间:2017-10-30 00:44:38

标签: sql sql-server tsql ssms

我正在使用Microsoft示例数据库AdventureWorksLT2012学习T-SQL。我试图获得每种产品的销售百分比。此刻我有这样的查询:

USE AdventureWorksLT2012;
GO

SELECT ProductTable.Name, TotalOrderItemsTable.TotalOrderedItems
FROM SalesLT.Product ProductTable INNER JOIN 
(SELECT ProductID, COUNT(*) As TotalOrderedItems
FROM SalesLT.SalesOrderDetail TotalOrderTable
GROUP BY ProductID) TotalOrderItemsTable ON ProductTable.ProductID = TotalOrderItemsTable.ProductID

到目前为止的输出:

Name                     TotalOrderedItems
AWC Logo Cap            |9
Bike Wash - Dissolver   |7
Chain                   |4
Classic Vest, M         |6
Classic Vest, S         |10
Front Brakes            |7

期望的输出:

Name                     PercentageSale
AWC Logo Cap            |20.9...
Bike Wash - Dissolver   |16.2...
Chain                   |9.3...
Classic Vest, M         |14.0...
Classic Vest, S         |23.2...
Front Brakes            |16.2..

我正在尝试构建一个类似TotalOrderedItems / SUM(TotalOrderedItems)的查询* 100

SELECT ProductTable.Name, TotalOrderItemsTable.TotalOrderedItems / SUM(TotalOrderedItems) * 100

但是我觉得还没有计算SUM(TotalOrderedItems),因此给了我错误。

任何想法我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

您可以使用窗口函数SUM获取百分比。 SUM(COUNT(*)) OVER()会给出所有产品的订购商品总数。

SELECT p.ProductID, p.Name, 100.0*COUNT(*)/SUM(COUNT(*)) OVER() as pct
FROM SalesLT.Product p
INNER JOIN SalesLT.SalesOrderDetail s ON p.ProductID = s.ProductID
GROUP BY p.ProductID, p.Name

现有的查询也可以扩展。

SELECT p.ProductID, p.Name, 100.0*s.TotalOrderedItems/sum(s.TotalOrderedItems) as pct
FROM SalesLT.Product p
INNER JOIN (SELECT ProductID, COUNT(*) As TotalOrderedItems
            FROM SalesLT.SalesOrderDetail TotalOrderTable
            GROUP BY ProductID) s ON p.ProductID = s.ProductID
GROUP BY p.ProductID, p.Name

答案 1 :(得分:0)

另一个选项是使用窗口函数

示例

Select *
      ,PercentageScale = (TotalOrderedItems * 100.0)/sum(TotalOrderedItems) over () 
from  YourTable

<强>返回

Name                    TotalOrderedItems   PercentageScale
AWC Logo Cap            9                   20.930232558139
Bike Wash - Dissolver   7                   16.279069767441
Chain                   4                   9.302325581395
Classic Vest, M         6                   13.953488372093
Classic Vest, S         10                  23.255813953488
Front Brakes            7                   16.279069767441

答案 2 :(得分:0)

我认为您想要的查询是:

SELECT p.ProductID, p.Name, 
       COUNT(*) * 100.0 / SUM(SUM(COUNT(*))) OVER () as pct
FROM SalesLT.Product p JOIN
     SalesLT.SalesOrderDetail s
     ON p.ProductID = s.ProductID
GROUP BY p.ProductID, p.Name;

子查询是不必要的。