我有以下查询:
查询1
查询2
查询 3
如何将它们合并为一个查询? 我需要第四个查询的结果。
查询1
SELECT so.ClientID, 'All Channels' as CustomerGroup, so.StatementID, so.Brand, so.Product,
Sum(so.Amount) Amount, Sum(so.Value_CP) Value_CP
into #t1
FROM RG_SalesOut_Report so
WHERE so.Block=0 AND so.[All Sources]='SalesOUT'AND so.Value_CP>0 AND so.Amount>0 AND
so.Brand in('Brand 1', 'Brand 2')
GROUP BY so.ClientID, so.CustomerGroup, so.StatementID, so.Brand, so.Product
查询2
select t1.ClientID, t1.CustomerGroup, t1.StatementID, t1.Brand, t1.Product,
Sum(t1.Amount) AS Amount, Sum(t1.Value_CP) AS Value_CP
into #t2
from #t1 t1
group by t1.ClientID, t1.CustomerGroup, t1.StatementID, t1.Brand, t1.Product
查询 3
select ROW_NUMBER() over(order by t2.ClientID desc) as ID, *, CONCAT(t2.ClientID, t2.Product) AS Code
into #t3
from #t2 t2
group by t2.ClientID, t2.CustomerGroup, t2.StatementID, t2.Brand, t2.Product, t2.Amount, t2.Value_CP, CONCAT(t2.ClientID, t2.Product)
ORDER BY t2.ClientID DESC, t2.Product, t2.StatementID desc
查询 4
select tab1.ClientID, tab1.CustomerGroup, convert(varchar,(CONVERT(date,tab1.StatementID,104)),104) AS StatementID, tab1.Brand,
tab1.Product, tab1.Amount, tab1.Value_CP, IIF(tab1.code=tab2.code, DATEDIFF(MONTH,tab2.StatementID, tab1.StatementID), 0) AS M_SALES
FROM #t3 tab1
RIGHT JOIN #t3 tab2
ON tab1.ID=tab2.ID-1
where tab1.StatementID >= '01.01.2013'
order by tab1.ID asc
如何将它们合并为一个查询? 我需要第四个查询的结果。
UNION
或UNION ALL
。 - Milen