繁体   English   中英

MySQL查询,在其中一个表中组合了两个表和两列

[英]MySQL query that combines two tables and two columns in one of the tables

我正在尝试编写一个SQL查询,在其中一个表中组合了两个表和两个列。 所以,我有两张桌子

表: Items

ID          Material           Shape

1           glass              jar
2           plastic            bottle
3           cardboard          box
4           glass              bottle

表: Diary

ItemID      UserID      Quantity

2           1           1
1           1           3
3           1           2
2           1           5
4           1           1

UserID = 1预期输出(按combined quantity排序):

Combined column values       Combined quantity

plastic bottle               6
glass jar                    3
cardboard box                2
glass bottle                 1

有人能以正确的方式指导我吗?

我认为这只是一个joingroup by

select concat_ws(' ', i.material, i.shape) as combined,
       sum(d.quantity) as combined_quantity
from items i left join
     diary d
     on d.itemId = i.id
group by combined
order by combined_quantity desc;

询问

select Material+SPACE(1)+ SHAPE [Combined column values ], 
SUM(QUANTITY) [Combined quantity]
from Items 
left join diary on Items.itemiD = diary.itemID  
GROUP BY ITEMS.itemiD, Material, SHAPE 

产量

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM