不同WHERE的相同聚合函数

时间:2015-02-03 12:08:01

标签: sql sql-server where

我陷入了困境。试图弄清楚如何使用像SUM(column1 * column2)这样的聚合函数来生成多列结果。我想打印前。 SUM(qty * unitprice)其中“blabla”和“blabla”之间的orderdate,

然后我想要另一个使用相同功能的列(sum(qty * unitprice) 但在where子句中有其他表达式。这是我的代码示例,它没有显示任何内容:

select Orderdates, Sales, SalesDisc
FROM (  select month(OH.OrderDate) as Orderdates, sum(OD.OrderQty*OD.UnitPrice) as Sales
        from sales.SalesOrderDetail OD
        inner join sales.salesorderheader OH on
        OD.SalesOrderID = OH.SalesOrderID
        where OrderDate >= ('2014-01-01') and OrderDate < ('2015-01-01')
        group by month(OH.orderdate)    
     ) A 

     Join
        (select month(OH.OrderDate) as orderdatez, sum(OD.OrderQty*OD.UnitPrice) as SalesDisc
        from sales.SalesOrderDetail OD
        inner join sales.SalesOrderHeader OH on 
        OD.SalesOrderID = OH.SalesOrderID
        where OrderDate >= ('2014-01-01') and OrderDate < ('2015-01-01')
        and OD.SpecialOfferID between 2 and 16
        Group by Month(OH.orderdate)
        ) B
        on A.Orderdates = B.orderdatez and A.Sales = B.SalesDisc

1 个答案:

答案 0 :(得分:3)

如果没有错,这就是你需要的

SELECT Month(OH.OrderDate)             AS Orderdates,
       Sum(OD.OrderQty * OD.UnitPrice) AS Sales,
       Sum(CASE
             WHEN OD.SpecialOfferID BETWEEN 2 AND 16 THEN ( OD.OrderQty * OD.UnitPrice )
             ELSE 0
           END)                        AS SalesDisc
FROM   sales.SalesOrderDetail OD
       INNER JOIN sales.salesorderheader OH
               ON OD.SalesOrderID = OH.SalesOrderID
WHERE  OrderDate >= ( '2014-01-01' )
       AND OrderDate < ( '2015-01-01' )
GROUP  BY Month(OH.orderdate) 

注意:如果您在year(OH.orderdate)

中添加group by,会更有意义