将查询合并为一个

时间:2014-06-18 08:07:18

标签: sql sql-server

我有以下问题:

查询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

如何将它们合并为一个查询? 我需要查询4结果

1 个答案:

答案 0 :(得分:1)

如果使用SQLServer,则可以使用Common table expression而不插入临时表。此外,您在#T3查询中不需要order by类:

WITH T1 AS 
(
SELECT so.ClientID, 'All Channels' as CustomerGroup, so.StatementID, so.Brand, so.Product,
Sum(so.Amount) Amount, Sum(so.Value_CP) Value_CP
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 
),
T2 AS
(
select t1.ClientID, t1.CustomerGroup, t1.StatementID, t1.Brand, t1.Product,
Sum(t1.Amount) AS Amount, Sum(t1.Value_CP) AS Value_CP
from T1
group by t1.ClientID, t1.CustomerGroup, t1.StatementID, t1.Brand, t1.Product
),
T3 AS
(
select ROW_NUMBER() over(order by t2.ClientID desc) as ID, *, CONCAT(t2.ClientID, t2.Product) AS Code
from t2
group by t2.ClientID, t2.CustomerGroup, t2.StatementID, t2.Brand, t2.Product, t2.Amount, t2.Value_CP, CONCAT(t2.ClientID, t2.Product)
)

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