然后我想要另一个使用相同功能的列(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
答案 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
,会更有意义