PIVOT SQL Server 协助
给定以下表结构:
CrimeID | No_Of_Crimes | CrimeDate | Violence | Robbery | ASB
1 1 22/02/2011 Y Y N
2 3 18/02/2011 Y N N
3 3 23/02/2011 N N Y
4 2 16/02/2011 N N Y
5 1 17/02/2011 N N Y
是否有可能使用 T-SQL 生成如下所示的结果集?
Category | This Week | Last Week
Violence 1 3
Robbery 1 0
ASB 3 1
上周的数据应该小于“20/02/2011”,而本周的数据应该大于或等于“20/02/2011”,
我不是在寻找有人为我编码,尽管有一个代码代码片段会很方便:),只是一些关于这是否可能的建议,以及我应该如何使用 SQL Server 来实现它。
有关信息,我目前正在 Web 服务器上使用 LINQ 执行所有这些聚合,但这需要每次发出此请求时通过网络发送 19MB。 (该表有很多类别,并且 > 150,000 行)。我想让数据库完成所有工作,只通过网络发送少量数据
非常感谢
Given the following table structure:
CrimeID | No_Of_Crimes | CrimeDate | Violence | Robbery | ASB
1 1 22/02/2011 Y Y N
2 3 18/02/2011 Y N N
3 3 23/02/2011 N N Y
4 2 16/02/2011 N N Y
5 1 17/02/2011 N N Y
Is there a chance of producing a result set that looks like this with T-SQL?
Category | This Week | Last Week
Violence 1 3
Robbery 1 0
ASB 3 1
Where last week shuld be a data less than '20/02/2011' and this week should be greater than or equal to '20/02/2011'
I'm not looking for someone to code this out for me, though a code snippet would be handy :), just some advice on whether this is possible, and how i should go about it with SQL Server.
For info, i'm currently performing all this aggregation using LINQ on the web server, but this requires 19MB being sent over the network every time this request is made. (The table has lots of categories, and > 150,000 rows). I want to make the DB do all the work and only send a small amount of data over the network
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了清楚起见,编辑删除了不正确的sql
编辑忘记上面的尝试下面的
EDIT removed incorrect sql for clarity
EDIT Forget the above try the below
虽然迟到了,但有一个具有最佳查询计划的解决方案:
示例数据
制作更多数据 - 除了上述 5 行之外,总共约 10240 行,每 5 行比前 5 行早 2 周。同时创建一个索引,这将有助于在
犯罪日期
。从这里开始,检查每个的输出以了解其进展情况。还要检查执行计划。
标准 Unpivot 打破类别。
注意:
再次逆透视,但这次仅选择上周和本周的数据。
注意:
(select DATEADD(wk, DateDiff(wk, 0, getdate()), 0)) w(firstDayThisWeek)
创建一个单列表,其中列包含此查询的关键日期,是本周的第一天(使用 DATEFIRST 设置)Sign()
只是将数据分成 3 个桶 (-1/0/+1)。添加+0.1确保只有两个桶-1和+1。最终查询,按本周/上周
输出旋转
Late to the party, but a solution with an optimal query plan:
Sample data
Make more data - about 10240 rows in total in addition to the 5 above, each 5 being 2 weeks prior to the previous 5. Also create an index that will help on
crimedate
.From here on, check output of each to see where this is going. Check also the execution plan.
Standard Unpivot to break the categories.
Notes:
Unpivot again, but this time select data only for last week and this week.
Notes:
(select DATEADD(wk, DateDiff(wk, 0, getdate()), 0)) w(firstDayThisWeek)
makes a single-column table where the column contains the pivotal date for this query, being the first day of the current week (using DATEFIRST setting)Sign()
just breaks the data into 3 buckets (-1/0/+1). Adding +0.1 ensures that there are only two buckets -1 and +1.The final query, pivoting by this/last week
Output
我会尝试这个:
I would try this: