gpt4 book ai didi

sql - SUM SQL Select 的某些列与两个表的 UNION

转载 作者:行者123 更新时间:2023-12-01 22:35:17 25 4
gpt4 key购买 nike

我有这个问题

SELECT Month(date) AS Monthly, Year(date) AS Annual, COUNT(idcad) AS NumCad, SUM(CONVERT(FLOAT, valorpag)) AS Valor FROM PI_AS
WHERE (status = 'Paid' OR status = 'Available') AND platform = 'Sales'
GROUP BY Year(date), Month(date)
ORDER BY Year(date), Month(date)

示例结果:

Monthly | Annual | NumCad | Valor
3 | 2014 | 62 | 72534
4 | 2014 | 7 | 8253.6
5 | 2014 | 42 | 45356.39
6 | 2014 | 36 | 33343.19
7 | 2014 | 5 | 4414.6

和这个查询

SELECT Month(date) AS Monthly, Year(date) AS Annual, COUNT(idcad) AS NumCad, SUM(CONVERT(FLOAT, valorpag)) AS Valor FROM PI_PP
WHERE (status = 'Completed') AND platform = 'Sales'
GROUP BY Year(date), Month(date)
ORDER BY Year(date), Month(date)

示例结果:

Monthly | Annual | NumCad | Valor
4 | 2014 | 6 | 2572.80
5 | 2014 | 8 | 7828
6 | 2014 | 3 | 3891.60
7 | 2014 | 2 | 278.3

我尝试了 UNION 查询:

SELECT Month(date) AS Monthly, Year(date) AS Annual, COUNT(idcad) AS NumCad, SUM(CONVERT(FLOAT, valorpag)) AS Valor FROM PI_AS
WHERE (status = 'Paid' OR status = 'Available') AND platform = 'Sales'
GROUP BY Year(date), Month(date)
UNION
SELECT Month(date) AS Monthly, Year(date) AS Annual, COUNT(idcad) AS NumCad, SUM(CONVERT(FLOAT, valorpag)) AS Valor FROM PI_PP
WHERE (status = 'Completed') AND platform = 'Sales'
GROUP BY Year(date), Month(date)
ORDER BY Year(date), Month(date)

但是当我这样做时,它会重复同一个月的行...我想要同一个月的 NumCadValor 的 SUM

UNION 结果是这样的:

Monthly | Annual | NumCad | Valor
6 | 2014 | 3 | 3891.60
6 | 2014 | 36 | 33343.19
7 | 2014 | 5 | 4414.6
7 | 2014 | 2 | 278.3

但我想要这个:

Monthly | Annual | NumCad | Valor
6 | 2014 | 39 | 37234.79
7 | 2014 | 7 | 4692.9

有什么想法吗?

最佳答案

首先您需要对数据运行联合,然后进行聚合:

SELECT 
Month(data.date) AS Monthly,
Year(data.date) AS Annual,
COUNT(data.idcad) AS NumCad,
SUM(CONVERT(FLOAT, data.valorpag)) AS Valor
FROM
(SELECT date, idcad, valorpag FROM PI_AS
WHERE (status = 'Paid' OR status = 'Available') AND platform = 'Sales'
UNION ALL
SELECT date, idcad, valorpag FROM PI_PP
WHERE (status = 'Completed') AND platform = 'Sales'
) data
GROUP BY Year(data.date), Month(data.date)
ORDER BY Year(data.date), Month(data.date)

关于sql - SUM SQL Select 的某些列与两个表的 UNION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24536896/

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