gpt4 book ai didi

sql - 将查询合并为一个

转载 作者:行者123 更新时间:2023-12-02 09:21:08 24 4
gpt4 key购买 nike

我有以下疑问:

查询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 ​​结果

最佳答案

如果您使用 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

关于sql - 将查询合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24280227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com