帮助解决困难的“分组依据”条款
需要您的帮助来进行查询。
我有一个表 Managers (ManagerId, ManagerName)
我有一个表 Statuses (StatusId, StatusName)
(该表中有大约 10 个状态)
我有一个表 Clients (ClientId, ClientName, ManagerId, StatusId, WhenAdded)
(WhenAdded
是日期时间类型)
很明显,字段 'ManagerId'
引用了表 'Managers'
并且字段'StatusId'
引用表'Statuses'
。
用户希望获取下表中一段时间内(从 startDate 到 endDate,使用字段“WhenAdded”
)有关经理的一些统计信息。
列:
ManagerName、NumberOfClients、NumberOfClientsWithStatus1、NumberOfClientsWithStatus2、NumberOfClientsWithStatus3
等。
名称为 NumberOfClientsWithStatusI
的列数,其中 i
是等于表 'Statuses'
中的行数的状态数。
我怎样才能做到这一点?
t-sql,sql server 2008 r2 快捷版。
need some your help with a query.
I have a table Managers (ManagerId, ManagerName)
I have a table Statuses (StatusId, StatusName)
(There's about 10 statuses in that table)
I have a table Clients (ClientId, ClientName, ManagerId, StatusId, WhenAdded)
(WhenAdded
is a datetime type)
It's obvious that field 'ManagerId'
refers to a table 'Managers'
and field 'StatusId'
refers to a table 'Statuses'
.
User wants to get some statistics about Managers over a period of time (from startDate to endDate using field 'WhenAdded'
) in the following table.
Columns:
ManagerName, NumberOfClients, NumberOfClientsWithStatus1, NumberOfClientsWithStatus2, NumberOfClientsWithStatus3
and so on.
Number of columns with name NumberOfClientsWithStatusI
where i
is a number of statuses equal to number of rows in table 'Statuses'
.
How can I do that?
t-sql, sql server 2008 r2 express edition.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
注意:没有干净的方法可以在 SQL(不仅仅是 SQL Server)中添加任意数量的状态列,因为它是固定列输出。您必须更改状态查询,除非您
在评论后在客户端编辑中处理此问题
Note: there is no clean way to add arbritrary numbers of status columns in SQL (not just SQL Server) because its a fixed column output. You'd have to change the query for status, unless you deal with this in the client
Edit, after comment
如果您知道
statuses
表将始终包含有限数量的状态,您可以执行以下操作:If you know that
statuses
table will always contain a limited number of statuses, you can do this: