SQL动态列查询

发布于 2024-10-09 03:25:42 字数 1061 浏览 1 评论 0原文

可能的重复:
有没有办法创建一个 SQL Server 函数来将子查询中的多行“连接”到单个分隔字段中?

我有一个“事件”表,每个事件都有一个 1-4 的列表(本质上是变量#)“用户”。假设我获取了今天的所有事件,然后我想将用户列为动态数量的列,而不是重复的行。

现在,

SELECT E.EventID, E.Time, U.Name FROM Events
INNER JOIN Users U ON E.UserID = U.UserID
WHERE Date = '12/20/2010'

这给我带来了这样的结果:

EventID, Time, Name
211, '4:00am', 'Joe'
211, '4:00am', 'Phil'
211, "4:00am', 'Billy'
218, '7:00am', 'Sally'
218, '7:00am', 'Susan'

我可以使用它并且它是可以接受的,但是 EventID 和 Time 的重复(我的实际查询中有更多列)对我来说似乎很浪费。我真正想要的输出是这样的:

EventID, Time, Name1, Name2, Name3
211, '4:00am', 'Joe', 'Phil', 'Billy'
218, '7:00am', 'Sally', 'Susan', NULL

我尝试查看 PIVOT 教程(我有 SQL 2008),但我不知道它们在概念上是否与我想要做的相匹配。他们中的大多数都使用“MIN”或“MAX”。

也许这不能做到?我的另一个选择是获取今天的事件列表,然后循环遍历该列表,找到该事件的用户记录集。不过,我更愿意在一个查询中获取所有内容。

有什么想法吗?

Possible Duplicate:
Is there a way to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

I have a table of "Events", and each event has a a list of 1-4 (essentially variable #) "Users". So let's say I get all events for today, and then I want to list the users as a dynamic number of columns, rather than repeated rows.

Right now I have

SELECT E.EventID, E.Time, U.Name FROM Events
INNER JOIN Users U ON E.UserID = U.UserID
WHERE Date = '12/20/2010'

This brings me results like:

EventID, Time, Name
211, '4:00am', 'Joe'
211, '4:00am', 'Phil'
211, "4:00am', 'Billy'
218, '7:00am', 'Sally'
218, '7:00am', 'Susan'

I can work with this and it's acceptable, however the duplication for EventID and Time (there are more columns in my actual query) seems wasteful to me. What I would really like in the output is this:

EventID, Time, Name1, Name2, Name3
211, '4:00am', 'Joe', 'Phil', 'Billy'
218, '7:00am', 'Sally', 'Susan', NULL

I have tried looking at tutorials for PIVOTs (I have SQL 2008), but I don't know if they conceptually match what I'm trying to do. Most of them are using "MIN" or "MAX".

Maybe this can't be done? My other alternative is to get a list of Events for today, and then loop through that, finding a recordset of Users for that Event. I would prefer to grab it all in one query though.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亢潮 2024-10-16 03:25:42

返回可变数量的列将更难在代码中处理。您当前获得的结果集很容易转换为您可以在代码中使用的对象。

您想对输出做什么?

Returning a variable number of columns would be harder to deal with in code. The result set you are currently getting is easy to transform into an object that you can worth with in code.

What are you trying to do with the output?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文