如何用逗号分隔从 SQL 查询获得的多行
Select s.FirstName, glTitle.LookupItem Title
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join StaffTitle st on st.StaffId = s.Id
left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
它返回这些行:
正如您所看到的,第一列具有所有相同的行,因为一名员工可以拥有多个头衔。
如何将每个员工的所有头衔合并为逗号分隔值,以便每个员工只有一行?
Select s.FirstName, glTitle.LookupItem Title
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join StaffTitle st on st.StaffId = s.Id
left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
It returns these rows:
As you can see, the first column has all same rows because one employee can have multiple titles.
How can I merge all of the titles for each employee into a comma separated value so that there is only one row per employee?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这对我有用:
This worked for me:
我通常创建 SQL 函数并从查询中调用它们。您可以使用多种方法创建逗号分隔的值列表,请参阅 http://blog.sqlauthority.com/2008/06/04/sql-server-create-a-comma-delimited-list -using-select-clause-from-table-column/,我可以用逗号将多行分隔成一列吗?。
在这种情况下,如果您创建一个函数,则可以从 SQL 查询中调用它。像这样的东西:
I usually create SQL functions and call them from my queries. You can create a comma delimited list of values using a multitude of approaches, see http://blog.sqlauthority.com/2008/06/04/sql-server-create-a-comma-delimited-list-using-select-clause-from-table-column/, Can I Comma Delimit Multiple Rows Into One Column?.
In this case if you create a function, you can then call it from your SQL query. Something like:
这是在标准 SQL 中很难(或不可能)做到的事情之一。许多供应商已经扩展了 SQL 以支持这样的“汇总”;不幸的是,每个供应商的语法都不同。抱歉,我目前没有方便的示例。那么您使用的是什么 DBMS?
This is one of those things that's difficult (or impossible) to do in standard SQL. Many vendors have extended SQL to support "rollups" like that; unfortunately, each vendor's syntax is different. Sorry, I don't have an example handy at the moment. So what DBMS are you using?
尝试这样的事情:
无法真正测试,所以它很困难,尝试和错误通常最终会起作用。不过,我建议按唯一的 id 进行分组。
我希望这有帮助...
Try something like:
Cant really test, so its difficult, trail and error usually works eventually. I would suggest to group by a unique id though.
I hope this helps...
您可以使用此查询。我有针对遵循此模式的此类查询的通用模板。您可能必须对此进行调试,因为我没有您的表结构。它将标题合并到一个列表中
You can use this query. I have generic template for queries like these that follows this pattern. You might have to debug this because I don't have your table structure. It coalesces the titles into a list