gpt4 book ai didi

Mysql内连接或左连接

转载 作者:行者123 更新时间:2023-11-30 21:50:21 27 4
gpt4 key购买 nike

我有 1 个表产品,我想提取 A 和 B 类型产品的价格。我尝试使用 INNER JOIN 但它返回重复记录。我该怎么做?

 id   |   Price    |     Date    |   Type   |   Size  |
-------------------------------------------------------
1 | 1,00 | 01/11/2010 | A | 7,00 |
2 | 2,50 | 02/11/2010 | A | 8,00 |
3 | 2,50 | 03/11/2010 | A | 9,00 |
4 | 3,00 | 02/11/2010 | A | 10,00 |
5 | 4,00 | 03/11/2010 | A | 11,00 |
6 | 4,00 | 03/11/2010 | A | 12,00 |
7 | 5,00 | 03/11/2010 | A | 13,00 |
8 | 5,00 | 03/11/2010 | A | 14,00 |
9 | 6,00 | 03/11/2010 | A | 15,00 |
10 | 7,00 | 03/11/2010 | A | 16,00 |
11 | 1,00 | 03/11/2010 | B | 17,00 |
12 | 2,50 | 03/11/2010 | B | 18,00 |
13 | 3,00 | 03/11/2010 | B | 19,00 |
14 | 3,00 | 03/11/2010 | B | 20,00 |
15 | 5,00 | 03/11/2010 | B | 21,00 |
16 | 6,00 | 03/11/2010 | B | 22,00 |
17 | 7,00 | 03/11/2010 | B | 23,00 |
18 | 7,00 | 03/11/2010 | B | 24,00 |

我想建立一个这样的表:

 Price    |     Date    |   Size A |   Size B  |
-------------------------------------------------------
1,00 | 01/11/2010 | 7,00 | 17,00 |
2,50 | 02/11/2010 | 8,00 | |
2,50 | 03/11/2010 | 9,00 | 18,00 |
3,00 | 02/11/2010 | 10,00 | 19,00 |
4,00 | 03/11/2010 | 11,00 | |
4,00 | 04/11/2010 | 12,00 | |
5,00 | 03/11/2010 | 13,00 | 21,00 |
5,00 | 04/11/2010 | 14,00 | |
6,00 | 05/11/2010 | 15,00 | |
7,00 | 06/11/2010 | 16,00 | 23,00 |

我怎样才能在一次查询中做到这一点?

感谢您的帮助。

最佳答案

select price, 
date,
sum(case when `type` = 'A' then size else 0 end) as SizeA,
sum(case when `type` = 'B' then size else 0 end) as SizeB
from products
group by price, date
order by price, date

日期 分组以获取每个日期的数据。要获取其他列,您需要使用聚合函数,例如 sum()

如果您确实需要 null 值,您可以这样做:

case when sum(`type` = 'A') = 0 
then null
else sum(case when `type` = 'A' then size end)
end

关于Mysql内连接或左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47572793/

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