SQL查询问题
我目前正在学习 SQL,并且在计算如何执行以下操作时遇到一些问题:
表:
Planned Order
id Item Date
0 1 2011-01-24
1 1 2011-01-26
2 1 2011-01-28
3 2 2011-01-24
4 3 2011-01-27
Customer Order
id Item Date
4 2 2011-01-25
3 2 2011-01-24
2 2 2011-01-24
1 1 2011-01-26
0 1 2011-01-24
我正在尝试生成以下查询,该查询将生成:
Item Category 2011-01-24 2011-01-25 2011-01-26
1 Customer_Order 1 NULL 1
1 Planned_Order 1 NULL 1
2 Customer_Order 2 NULL NULL
2 Planned_Order 1 NULL NULL
3 Planned_Order NULL NULL NULL
日期下的计数是当天订购该商品的次数。
这是否可以通过原始 sql 代码实现,或者是这样吗?我意识到这可以通过其他语言(例如 perl)来操作数据并通过多个数据库访问来完成,但我想直接从原始 sql 来完成此操作。
我找不到命令(原始sql)来将查询从列转换为行。我如何查询日期并为每个日期生成列,如上所示。
I'm currently learning SQL and have some issues figuring how to do the following:
Tables:
Planned Order
id Item Date
0 1 2011-01-24
1 1 2011-01-26
2 1 2011-01-28
3 2 2011-01-24
4 3 2011-01-27
Customer Order
id Item Date
4 2 2011-01-25
3 2 2011-01-24
2 2 2011-01-24
1 1 2011-01-26
0 1 2011-01-24
I'm trying to produce the following query that will produce:
Item Category 2011-01-24 2011-01-25 2011-01-26
1 Customer_Order 1 NULL 1
1 Planned_Order 1 NULL 1
2 Customer_Order 2 NULL NULL
2 Planned_Order 1 NULL NULL
3 Planned_Order NULL NULL NULL
Where the count under the date is how many times the item was ordered that day.
Is this even possible with raw sql code or is this? I realize this can be done through other languages such as perl to manipulate the data and through multiple data base access, but I wanted to do this directly from raw sql.
I can't find a command(raw sql) to convert a query from a column and convert it to a row. How I query the dates and produce column for each date like seen above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Sql Server (2005/2008) 中,有一个操作符可以完全满足您的需要 (PIVOT)
In Sql Server (2005/2008), there´s an operator to do exactly what you need (PIVOT)
进行旋转的便携式方法:
问题是您需要知道要预先显示的所有日期。据我所知,唯一支持动态列列表的 DBMS 是 Oracle。其他 DBMS 将要求您生成动态 SQL 来创建 CASE 语句,每个语句对应遇到的每个不同日期。
唯一不可移植的部分是,由于使用日期作为字段名称,您需要
Portable way to do Pivoting:
The problem is that you need to know all the dates you want to display up front. The only DBMS (I know of) to support a dynamic list of columns is Oracle. Other DBMS will require you to generate dynamic SQL to create the CASE statements, one for each distinct date encountered.
The only non-portable part is that because of using dates as field names, you need