SQL - 将多行数据移动到一行
我想做的是从一列中获取多行数据并将其插入到一个单元格中。以下是我的内容:
+++HouseNumber+++++++CustomerType+++
+ 1 + Residential +
+ 2 + Commercial +
+ 2 + Residential +
+ 3 + Residential +
++++++++++++++++++++++++++++++++++++
我需要将其变成如下所示:
+++HouseNumber+++++++CustomerType+++++++++++++++
+ 1 + Residential +
+ 2 + Commercial Residential +
+ 3 + Residential +
++++++++++++++++++++++++++++++++++++++++++++++++
我意识到这违反了规范化;但是,我只需要以这种方式显示这些数据,以便以后可以更轻松地查看它,特定单元格将永远不会再被其中的任何单个项目引用。
我尝试通过创建两个表来做到这一点,一个具有 tempCustomerType,另一个具有原始 NULL 的 customerType 字段,然后使用以下内容进行更新:
UPDATE CustomerIdentifier
SET CustomerIdentifier.CustomerType = TempTable2.CustomerTypeTemp + CustomerIdentifier.CustomerType
FROM CustomerIdentifier
INNER JOIN TempTable2
ON CustomerIdentifier.SUB_ACCT_NO_OCI = TempTable2.SUB_ACCT_NO_OCI
但是,之后每个字段仍然为空。那么,这里有人可以帮助我吗?谢谢!
另外,如果有一种方法可以在不创建第二个表的情况下执行此操作,那就太好了。
What I am trying to do is take multiple rows of data from a column and insert it into a single cell. Here's what I have below:
+++HouseNumber+++++++CustomerType+++
+ 1 + Residential +
+ 2 + Commercial +
+ 2 + Residential +
+ 3 + Residential +
++++++++++++++++++++++++++++++++++++
And I need to get this to something that looks like this:
+++HouseNumber+++++++CustomerType+++++++++++++++
+ 1 + Residential +
+ 2 + Commercial Residential +
+ 3 + Residential +
++++++++++++++++++++++++++++++++++++++++++++++++
I realize that this is against the normalization thing; however, I simply need this data displayed this way so that I can view it more easily later on, the particular cell will never again be referenced for any individual item within it.
I tried to do this by creating two tables, one with a tempCustomerType, and one with a a customerType field orignally NULL and then update using the following:
UPDATE CustomerIdentifier
SET CustomerIdentifier.CustomerType = TempTable2.CustomerTypeTemp + CustomerIdentifier.CustomerType
FROM CustomerIdentifier
INNER JOIN TempTable2
ON CustomerIdentifier.SUB_ACCT_NO_OCI = TempTable2.SUB_ACCT_NO_OCI
However, after that each field was still null. So, any chance anyone here can help me? Thanks!
Also, if there is a way to do this without creating a second table, that would be great as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
T/SQL 中的 NULL + 1 总是返回 null;
描述了您问题的解决方案
NULL + 1 in T/SQL always will return null;
The solutions for you problem are described here
我们按照此处所述实现了自己的 CLR 聚合函数,然后您可以写:
We implemented our own CLR aggregate function as described here, you can then write:
下面是该问题的更简单的解决方案。不幸的是,未在我的机器上进行测试(sql server install borked),我将明天进行测试并在必要时编辑答案。
这适用于 SQL 2005 及更高版本,并且不需要任何 UDF 或 CLR。它也相当快。
Below a simpler solution to the problem. Unfortunately untested on my machine (sql server install borked), I will test tomorrow and edit the answer if necessary.
This will work with SQL 2005 and above and doesn't require any UDFs or CLR. It is also pretty fast too.