在 SQL 中合并两行 [英] Merge two rows in SQL
本文介绍了在 SQL 中合并两行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含以下信息的表格:
Assuming I have a table containing the following information:
FK | Field1 | Field2
=====================
3 | ABC | *NULL*
3 | *NULL* | DEF
有没有办法在表格上执行选择以获得以下内容
is there a way I can perform a select on the table to get the following
FK | Field1 | Field2
=====================
3 | ABC | DEF
谢谢
为了清晰起见修复 field2 名称
Fix field2 name for clarity
推荐答案
聚合函数可以帮到你.聚合函数忽略 NULLs
(至少在 SQL Server、Oracle 和 Jet/Access 上是这样),因此您可以使用这样的查询(在 SQL Server Express 2008 R2 上测试):
Aggregate functions may help you out here. Aggregate functions ignore NULLs
(at least that's true on SQL Server, Oracle, and Jet/Access), so you could use a query like this (tested on SQL Server Express 2008 R2):
SELECT
FK,
MAX(Field1) AS Field1,
MAX(Field2) AS Field2
FROM
table1
GROUP BY
FK;
我使用了 MAX
,但是任何从 GROUP BY
行中选择一个值的聚合都应该可以工作.
I used MAX
, but any aggregate which picks one value from among the GROUP BY
rows should work.
测试数据:
CREATE TABLE table1 (FK int, Field1 varchar(10), Field2 varchar(10));
INSERT INTO table1 VALUES (3, 'ABC', NULL);
INSERT INTO table1 VALUES (3, NULL, 'DEF');
INSERT INTO table1 VALUES (4, 'GHI', NULL);
INSERT INTO table1 VALUES (4, 'JKL', 'MNO');
INSERT INTO table1 VALUES (4, NULL, 'PQR');
结果:
FK Field1 Field2
-- ------ ------
3 ABC DEF
4 JKL PQR
这篇关于在 SQL 中合并两行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文