[英]SQL SELECT query to set values with same id on different columns
I currently have a table with two columns: 'id' and 'type'.我目前有一个包含两列的表:“id”和“type”。 There can be multiple rows with the same id, but a type cannot be used more than once for each id.可以有多个具有相同 id 的行,但每个 id 不能多次使用一个类型。 Example:例子:
id ID | type类型 |
---|---|
1 1 | type-1 1型 |
1 1 | type-2 2型 |
1 1 | type-3 3型 |
2 2 | type-1 1型 |
2 2 | type-2 2型 |
I would like to construct a SELECT query which from the table above, would take every id and output a string containing all the types with the same id.我想构造一个 SELECT 查询,它从上表中获取每个 id 和 output 一个包含具有相同 id 的所有类型的字符串。 Example:例子:
id ID | types类型 |
---|---|
1 1 | type-1,type-2,type-3 1 型、2 型、3 型 |
2 2 | type-1,type-2 1型,2型 |
However, I do not know how I can do this.但是,我不知道我该怎么做。 Can someone help, please?有人可以帮忙吗?
Use GROUP_CONCAT
with an appropriate ORDER BY
clause:将GROUP_CONCAT
与适当的ORDER BY
子句一起使用:
SELECT id,
GROUP_CONCAT(type ORDER BY CAST(SUBSTRING_INDEX(type, '-', -1) AS UNSIGNED)) AS types
FROM yourTable
GROUP BY id
ORDER BY id;
SELECT STRING_AGG(types,','),id
FROM dbo.yourTable
GROUP BY id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.