Mysql 连接两个表并将文本值合并到一列中
我有以下两个表,您也可以在Mysql 连接两个表并将文本值合并到一列中,mysql,sql,Mysql,Sql,我有以下两个表,您也可以在sqlfiddle中找到它们: 注意:每个产品都明确分配给一个采购渠道 现在,我想做一个查询,结果如下: Sales_Date Product Channel Sales_Quantity 2017-05-23 Product A Online_Local_Supplier 400 2018-09-10 Product A Store_Local_Supplier 200 201
sqlfiddle
中找到它们:
注意:每个产品都明确分配给一个采购渠道
现在,我想做一个查询,结果如下:
Sales_Date Product Channel Sales_Quantity
2017-05-23 Product A Online_Local_Supplier 400
2018-09-10 Product A Store_Local_Supplier 200
2018-12-14 Product B Store_Reseller 600
2019-01-03 Product B Store_Reseller 650
: : : :
: : : :
: : : :
如您所见,我想将销售渠道
和采购渠道
合并到一列中因此,我设置了以下查询:
SELECT
s.Sales_Date,
s.Product,
(Case sales_channel
When "Online" Then "Online"
When "Store" then "Store"
When "TradeFair" then "Traidfair"
ELSE "NoSalesChannel"
END) AS Channel,
s.Sales_Quantity
FROM Sales s
JOIN Purchasing p ON p.Product = s.Product
GROUP BY 1,2;
此查询正确地插入了
销售渠道
,但我必须如何更改它,才能将采购渠道
添加到它中,如我所需的结果所示?请尝试不同的:
SELECT distinct
s.Sales_Date,
s.Product,
concat(s.Sales_Channel, '_', p.Purchasing_Channel) as Chanel,
s.Sales_Quantity
FROM Sales s
JOIN Purchasing p ON p.Product = s.Product
尝试concat
和group by
SELECT
s.Sales_Date,
s.Product,
concat(s.Sales_Channel, '_', p.Purchasing_Channel) as Chanel,
s.Sales_Quantity
FROM Sales s
JOIN Purchasing p ON p.Product = s.Product
group by s.Sales_Date,
s.Product,
concat(s.Sales_Channel, '_', p.Purchasing_Channel),
s.Sales_Quantity
这将给您一个结果:
Sales_Date | Product | Chanel | Sales_Quantity
2017-05-23 Product A Online_Local_Supplier 400
2018-09-10 Product A Store_Local_Supplier 200
2018-12-14 Product B Store_Reseller 600
2019-01-03 Product B Store_Reseller 700
2019-02-15 Product B Online_Reseller 650
2019-03-20 Product A Online_Local_Supplier 380
2019-08-25 Product C TradeFair_Foreign_Import 120
2019-09-16 Product C Online_Foreign_Import 470
2019-09-16 Product A Store_Local_Supplier 920
2019-10-20 Product B TraidFair_Reseller 860
另外,请检查jarlh给您的所有评论
在似乎没有涉及p列的情况下,为什么要加入采购?您通常会将选择的列与选择的列进行分组,但设置函数的参数除外。在不涉及设置函数的情况下,为什么要分组?非常感谢这个全面的答案。
Sales_Date | Product | Chanel | Sales_Quantity
2017-05-23 Product A Online_Local_Supplier 400
2018-09-10 Product A Store_Local_Supplier 200
2018-12-14 Product B Store_Reseller 600
2019-01-03 Product B Store_Reseller 700
2019-02-15 Product B Online_Reseller 650
2019-03-20 Product A Online_Local_Supplier 380
2019-08-25 Product C TradeFair_Foreign_Import 120
2019-09-16 Product C Online_Foreign_Import 470
2019-09-16 Product A Store_Local_Supplier 920
2019-10-20 Product B TraidFair_Reseller 860