MySQL将行值与逗号等结合 [英] MySQL Combine row values with comma and more
本文介绍了MySQL将行值与逗号等结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一段时间以来,我一直在head头。主要不是要获得解决方案,而要如何运作。
I have been banging my head over this for a while. Mainly it's not about getting a solution BUT how it works. It would be great if you can give explanation on how the solution is implemented.
这只是示例数据,我正在处理5个带有内联SELECT语句的表。谢谢SQL Gurus。
This is just sample data, I am working with 5 tables with inline SELECT statements. Thank you SQL Gurus.
CREATE TABLE source
(
product varchar(20),
amount decimal
)
CREATE TABLE cat
(
category varchar(20),
product varchar(20)
)
插入样本数据:
Insert Sample Data:
INSERT INTO source (product, amount) VALUES
('product1', 1.00),
('product2', 2.00),
('product3', 1.50),
('product4', 5.25)
INSERT INTO cat (category, product) VALUES
('Shirts', 'product1'),
('Green Shirt', 'product1'),
('Gadget', 'product1'),
('Food', 'product2'),
('Games', 'product4')
我的试用查询:
My Trial Query:
DECLARE @categories varchar(200)
SET @categories = NULL
SELECT
@categories = COALESCE(@categories + ',','') + cat.category
FROM cat
SELECT
DISTINCT source.product,
@categories
FROM cat
JOIN source on source.product = cat.product
输出
OUTPUT
PRODUCT COLUMN_1
product1 Shirts,Green Shirt,Gadget,Food,Games
product2 Shirts,Green Shirt,Gadget,Food,Games
product4 Shirts,Green Shirt,Gadget,Food,Games
期望的输出:
DESIRED OUTPUT:
PRODUCT COLUMN_1
product1 Shirts, Green Shirt, Gadget
product2 Gadget, Food
product4 Games
推荐答案
我认为这就是您要使用的东西 GROUP_CONCAT
:
I think this is what you're looking for using GROUP_CONCAT
:
SELECT
source.product,
GROUP_CONCAT(cat.category) cats
FROM cat
JOIN source on source.product = cat.product
GROUP BY source.product
如果您尝试在'bewe'中获取','在每个类别中,将 SEPARATOR
与 GROUP_CONCAT
结合使用。例如:
If you're trying to get a ', ' in between each category, use SEPARATOR
with GROUP_CONCAT
. For example:
GROUP_CONCAT(cat.category separator ', ')
这篇关于MySQL将行值与逗号等结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文