在子查询中汇总分组依据

时间:2019-04-06 19:08:56

标签: sql-server

试图在每一列中按特定销售人员的年份返回销售额,并在下一列中返回总销售额的百分比。

子查询应返回所有销售额的总计,因此可以计算百分比。但是该百分比是错误的,因为我无法聚合OrderDate,因为那样它将无法在join语句中识别(无法按YEAR(OrderDate)进行分组。任何见解都将是非常棒的。

SELECT Year(t1.OrderDate) as SalesYear,   sum(SubTotal+TaxAmt) as Sales,
    sum(SubTotal+TaxAmt)  / sum(YearlyGrandTotal) AS [Percent]
 FROM [AdventureWorks2017].[Sales].[SalesOrderHeader] t1
INNER JOIN (
    SELECT  OrderDate,Year(OrderDate) as O, sum(SubTotal+TaxAmt) as 
YearlyGrandTotal
    FROM Sales.SalesOrderHeader  
    GROUP BY (OrderDate)
) AS [Total] ON t1.OrderDate = Total.OrderDate
where SalesPersonID = 275

GROUP BY Year(t1.OrderDate)

1 个答案:

答案 0 :(得分:1)

使用group by year(orderdate)获取salessalespersonid = 275的{​​{1}},并将其用作子查询来计算百分比:

yearlygrandtotal