指定要在HAVING子查询中进行比较的列

问题描述 投票:0回答:1

[我正在尝试比较2014年Adventureworks中各商店不同季度的销售额。我的代码如下

SELECT store.BusinessEntityID as "StoreID",  "Name"
from sales.SalesOrderHeader
inner join sales.customer 
    on sales.SalesOrderHeader.CustomerID = sales.customer.CustomerID
inner join sales.store 
    on sales.customer.StoreID= sales.store.BusinessEntityID
where (OrderDate between '2014-01-01' and '2014-03-31')
    and (OnlineOrderFlag = 0)
group by store.BusinessEntityID, "Name"
having format(round(sum(subtotal),2),'###,###,###.##') > format(round(sum(subtotal),2),'###,###,###.##') IN
(
   SELECT store.BusinessEntityID as "StoreID",
   format(round(sum(subtotal),2),'###,###,###.##') "Ventes2013_Q4"
   from sales.SalesOrderHeader
   inner join sales.customer on sales.SalesOrderHeader.CustomerID =     sales.customer.CustomerID
   inner join sales.store on sales.customer.StoreID= sales.store.BusinessEntityID
   where (orderdate between '2013-10-01' and '2013-12-31') and OnlineOrderFlag = 0
   group by store.BusinessEntityID
) 

我的主查询和子查询都单独工作,但是我不能在hading的第二部分中指定要与之比较的列。尝试输入时,它给我提供了不正确的语法,并且在使用列名时也无法使用。在主查询中添加销售列时,它也不起作用谁能指出我正确的方向?

sql sql-server subquery ssms adventureworks
1个回答
0
投票
这是一种简单的方法(从您的代码翻译而来)

SELECT StoreID, Name FROM ( SELECT store.BusinessEntityID as "StoreID", "Name", sum(stubtotal) as sum from sales.SalesOrderHeader inner join sales.customer on sales.SalesOrderHeader.CustomerID = sales.customer.CustomerID inner join sales.store on sales.customer.StoreID= sales.store.BusinessEntityID where (OrderDate between '2014-01-01' and '2014-03-31') and (OnlineOrderFlag = 0) group by store.BusinessEntityID, "Name" ) first JOIN ( SELECT BusinessEntityID, sum(subtotal) as sum from sales.SalesOrderHeader inner join sales.customer on sales.SalesOrderHeader.CustomerID = sales.customer.CustomerID inner join sales.store on sales.customer.StoreID= sales.store.BusinessEntityID where (orderdate between '2013-10-01' and '2013-12-31') and OnlineOrderFlag = 0 group by store.BusinessEntityID ) as sub on sub.BusinessEntityID = furst.BusinessEntityID AND sub.sum < first.sum

但是在sql server中有更好的方法...一秒钟。
© www.soinside.com 2019 - 2024. All rights reserved.