简体   繁体   English

合并SQL行中的值

[英]Merge values in sql rows

I am looking for ways to merge row values into one row where the column to merge is the same 我正在寻找将行值合并到要合并的列相同的一行中的方法

Transform: 转变:

FK | F1 
========
3  | ABC    
3  | DEF 

to

FK | F1    | F2
=================
3  | ABC   | DEF

Update: I initially don`t know the values of F1. 更新:我最初不知道F1​​的值。 They might be everything, but I know they are unique for a given FK and they are varchars. 它们可能是一切,但我知道它们对于给定的FK是唯一的,并且它们是varchars。

Update 2: With your help I came to this query that will also add the FK for which there is only one value. 更新2:在您的帮助下,我来到了此查询,该查询还将添加只有一个值的FK。 I suppose it could be improved. 我想可以改进。

SELECT IFNULL(jointable.FK, table .FK) AS FK, IFNULL(jointable.F1, table .F1), jointable.F2 FROM table LEFT JOIN (SELECT T1.FK, T1.F1, T2.F1 AS F2 FROM table T1 LEFT JOIN table T2 ON T1.FK = T2.FK WHERE T1.F1 <> T2.F1 GROUP BY T1.FK ) as jointable ON table .FK=jointable.FK GROUP BY FK; SELECT IFNULL(jointable.FK, table .FK)AS FK,IFNULL(jointable.F1, table .F1),可连接F2 FROM table LEFT JOIN(SELECT T1.FK,T1.F1,T2.F1 AS F2 FROM table T1左联接table T2 ON T1.FK = T2.FK其中T1.F1 <> T2.F1 GROUP BY T1.FK)作为可联接的ON table .FK = jointable.FK GROUP BY FK;

Try this 尝试这个

SELECT FK
     , T1.F1
     , T2.F1 AS F2
FROM table T1
LEFT JOIN table T2 ON T1.FK = T2.FK AND T1.F1 <> T2.F1 --Criteria moved here

The LEFT JOIN is used since you mentioned that you have 1 or more values, which means the INNER JOIN could end up excluding rows. 因为您提到您有1个或多个值,所以使用了LEFT JOIN ,这意味着INNER JOIN可能最终会排除行。

The second criteria is to make sure you don't en up with rows like: 第二个条件是确保您不会遇到像这样的行:

FK | F1    | F2
=================
3  | ABC   | ABC

Please be aware that in case of an OUTER JOIN (either LEFT or RIGHT ) the join criteria is not the same as the filter criteria, and therefore I moved it above. 请注意,在使用外部OUTER JOINLEFTRIGHT )的情况下, OUTER JOIN条件与过滤条件不同,因此我将其移至上方。

In SQL Server, you can use ROW_NUMBER() over FK , maybe with an ORDER BY . 在SQL Server中,可以在FK使用ROW_NUMBER() ,也许可以使用ORDER BY

In MySQL you might be able to use it with a GROUP BY as you mentioned in comments, I am not sure it will work (at least not in SQL Server without an aggregate function or a CTE). 如注释中所述,在MySQL中您可能可以将其与GROUP BY一起使用,我不确定它是否可以工作(至少在没有聚合函数或CTE的SQL Server中不行)。

Here is a live test: http://ideone.com/Bu5aae 这是现场测试: http : //ideone.com/Bu5aae

A suggestion: 一条建议:

SELECT FK, CONCAT(T1.F1,'',T2.F1) AS Result
FROM table T1, table T2
WHERE T1.FK = T2.FK

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

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