sqlsql-serversubqueryssmsadventureworks

Specifying a column to compare in HAVING subquery


I am trying to compare sales from different quarters by stores in adventureworks 2014. My code is as following

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
) 

Both my main query and my subquery work individually, but I am not able to specify the column i want to compare it with in the second part of the having. When trying IN it gives me an incorrect syntax, and it does not work when using the column name either. It also did not work when adding a sales column in the main query Can anyone point me in the right direction?


Solution

  •  With Ventes2014_Q1 as(
    SELECT store.BusinessEntityID as "StoreID",  "Name",format(round(sum(subtotal),2),'###,###,###.##') "Ventes2014_Q1"
    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"
    ),Ventes2013_Q4
    (
       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
    ) 
    select "StoreID",  "Name" from Ventes2014_Q1 
    where "StoreID" exists 
            (select "StoreID" from Ventes2013_Q4 where Ventes2013_Q4."StoreID"=Ventes2014_Q1."StoreID" and Ventes2014_Q1."Ventes2014_Q1">Ventes2013_Q4."Ventes2013_Q4")