在 SQL 中合并两行
假设我有一个包含以下信息的表:
FK | Field1 | Field2
=====================
3 | ABC | *NULL*
3 | *NULL* | DEF
有没有一种方法可以在表上执行选择以获得以下
FK | Field1 | Field2
=====================
3 | ABC | DEF
感谢
编辑:为了清晰起见,修复 field2 名称
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
Thanks
Edit: Fix field2 name for clarity
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果有一张表,则写Table1而不是Table2
If there is one table, write Table1 instead of Table2
如果 field1 列中的一行具有值,而其他行具有空值,则此查询可能有效。
if one row has value in field1 column and other rows have null value then this Query might work.
我的情况是我有一个像这样的表
我希望它如下所示:
大多数代码几乎相同:
唯一的区别是
group by
,如果你在其中放入两个列名,你可以将它们成对分组。My case is I have a table like this
And I want it to be like below:
Most code is almost the same:
The only difference is the
group by
, if you put two column names into it, you can group them in pairs.可能有更简洁的方法,但以下可能是一种方法:
测试用例:
结果:
在没有
WHERE t.fk = 3
子句的情况下运行相同的查询,它将返回以下结果集:There might be neater methods, but the following could be one approach:
Test Case:
Result:
Running the same query without the
WHERE t.fk = 3
clause, it would return the following result-set:我有类似的问题。不同之处在于,我需要对返回的内容有更多的控制,因此我最终得到了一个简单清晰但相当长的查询。这是基于您的示例的简化版本。
这里的技巧是第一个选择“main”选择要显示的行。然后每个字段都有一个选择。连接的值应该与“主”查询返回的所有值相同。
请注意,其他查询只需为每个 id 返回一行,否则您将忽略数据
I had a similar problem. The difference was that I needed far more control over what I was returning so I ended up with an simple clear but rather long query. Here is a simplified version of it based on your example.
The trick here is that the first select 'main' selects the rows to display. Then you have one select per field. What is being joined on should be all of the same values returned by the 'main' query.
Be warned, those other queries need to return only one row per id or you will be ignoring data
聚合函数可能会帮助你。聚合函数忽略 NULL(至少在 SQL Server、Oracle 和 Jet/Access 上是这样),因此您可以使用这样的查询(在 SQL Server Express 2008 R2 上测试):
我使用了
MAX
,但任何从GROUP BY
行中选取一个值的聚合都应该有效。测试数据:
结果:
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):I used
MAX
, but any aggregate which picks one value from among theGROUP BY
rows should work.Test data:
Results:
根据您未包含的某些数据规则,有几种方法,但这是使用您提供的内容的一种方法。
另一种方式:
There are a few ways depending on some data rules that you have not included, but here is one way using what you gave.
Another way: