如何:使用 CTE 从非规范化数据中选择规范化视图?
这是一个非常标准的新手问题,但我正在寻找一种专家聪明的方法来用很少的代码来做到这一点。 (我知道如何使用程序代码和光标来完成这个长手操作,因此我们可以跳过答案的这一部分。)基本上,我有一个非标准化数据集,我需要在其中提取标准化表一套处理方式。原始数据来自 Excel,我将其作为表格附加到 MS SQL 中进行查询。单个字段(在 Excel 中,因此在 SQL 中)具有每个产品参与的部门的逗号分隔列表。
我知道我应该标准化数据,但它来自 Excel(用户这样做是不切实际的)。我知道我可以通过循环遍历每条记录的过程(如游标或 with 语句)来做到这一点,但这对于当今可用的工具来说似乎是不必要的。 是否有一个语句可以为这些记录提取带有“参与”字段的主键?
将源视为:
ProductIDDepartments
123 1,3,5,15
456 2,4,5,16
我从 dbo 进行了正常的 select * 操作。 split( CommaSepField) 但这一次仅适用于一条记录(并且您不能使用表值函数提供字段的值。更不用说,如何联合所有这些单个结果集?
联合所有结果集让我明白了考虑通用表表达式,但我不太清楚如何(1)使用扩展字段获取主键,以及(2)如何格式化查询以使其工作。
输出当然是:
ProductID。 部门
123 1
123 3
123 5
123 15
456 2
456 4
456 5
456 16
我在 StackOverflow 和 Google 上对此进行了相当多的研究,但并没有真正找到一个可以应用的答案。如果我错过了,我深表歉意。请发送链接:D。
This is a very standard newbie question, but I am looking for an expert clever way to do this with little code. (I know how to do this long hand, with procedural code and cursors, so we can skip that part of the answer.) Basically, I have a de-normalized data set for which I need to extract a normalized table in a set processing way. The raw data comes from Excel, which I attach as a table to query from MS SQL. A single field (in Excel and therefore SQL) has a comma separated list of departments that each product participates.
I know that I should normalize the data, but it is coming from Excel (and it is not practical for the user to do so). I know I can do this with a procedure to loop through each record (like a cursor or with statement) but that seems unnecessary with the tools available today. Is there a single statement where I can extract a primary key with a "participates" field for these records?
Think of the source as:
ProductIDDepartments
123 1,3,5,15
456 2,4,5,16
I did the normal select * from dbo.split( CommaSepField) but this only works on one record at a time (and you cannot provide a field's value in with a table valued function. Not to mention, how do you union all these single result sets?
Unionizing all the result sets got me thinking about Common Table Expressions, but I cannot quite figure out how to (1) get the primary key in with the expanded fields, and (2) how to format the query to work.
The output of course would be:
ProductIDDept
123 1
123 3
123 5
123 15
456 2
456 4
456 5
456 16
I researched this quite a bit in StackOverflow and Google, but didn't really find an answer that could apply. I apologize if I missed it. Please send links :D.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上可以使用逗号分隔 TVF,通过使用
CROSS APPLY 加入
运算符:You can actually use your comma separation TVF, by joining using the
CROSS APPLY
operator: