SQL Server 2008 +创建跨表存储过程
我有两个表想要连接并在 SQL 2008 中创建交叉表:
TableA:
Auto_ID | Fiscal_Period | Amount
1 | 01012012 | NULL
1 | 01022012 | 80
1 | 01032012 | NULL
2 | 01012012 | NULL
2 | 01022012 | 10
TABLEB:
Auto_ID | Row_ID | StaticData
1 | 1 | sampledata
2 | 2 | data1
我想使用交叉表动态创建以下表结构:
Row_ID | StaticData | FiscalPeriod(01012012) | FiscalPeriod(01022012) | FiscalPeriod(01032012)
1 | sampledata | NULL | 80 | NULL
2 | data1 | NULL | 10 | NULL
我当前的查询正确连接了表;但是,我很难将会计期间转入我的标题行。
SELECT *
FROM (SELECT
B.Row_Id as RowID, B.StaticData as StaticData, A.Fiscal_Period AS FPPD
FROM TableA A
LEFT JOIN TableB B ON A.Auto_ID = B.Auto_ID)
I have two tables that I want to join and create a crosstab table in SQL 2008:
TableA:
Auto_ID | Fiscal_Period | Amount
1 | 01012012 | NULL
1 | 01022012 | 80
1 | 01032012 | NULL
2 | 01012012 | NULL
2 | 01022012 | 10
TABLEB:
Auto_ID | Row_ID | StaticData
1 | 1 | sampledata
2 | 2 | data1
I would like to use cross table to dynamic create the following table structure:
Row_ID | StaticData | FiscalPeriod(01012012) | FiscalPeriod(01022012) | FiscalPeriod(01032012)
1 | sampledata | NULL | 80 | NULL
2 | data1 | NULL | 10 | NULL
My current query joins the tables correctly; however, I am having difficulty transposing the fiscal periods into my header row.
SELECT *
FROM (SELECT
B.Row_Id as RowID, B.StaticData as StaticData, A.Fiscal_Period AS FPPD
FROM TableA A
LEFT JOIN TableB B ON A.Auto_ID = B.Auto_ID)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是我要做的:
首先创建一些测试数据:
然后找到唯一的列:
然后使用动态 sql 执行数据透视:
然后在我的例子中我将删除临时表:
我希望这会对您有所帮助
This is what I would do:
First create some test data:
Then find the unique columns :
Then execute a pivot with dynamic sql:
Then in my case I will drop the temp tables:
I hope this will help you
由于您没有指定数据库类型,请注意,以下内容仅适用于 MySQL!
交叉表查询只能通过非常肮脏的技巧才能实现,它实际上只在存储过程中可行。
您首先想出某种方法,将会计周期列表转换为 SQL,例如
您现在必须将其构建为动态 SQL - 这仅在存储过程中可行。
诀窍是,将 SQL 构建到变量 @dynsql 中(DECLARE d 变量不起作用),然后准备并执行它。
现在查询
将创建您需要的输出。
Since you didn't specify a flavour of database, please mind, that the following is valid only for MySQL!
A cross-tab query is possible only with a very dirty trick, it is only practically feasable in a stored proc.
You start by thinking out some way, to transform a list of fiscal periods into SQL, something like
Which you now have to build as dynamic SQL - this is feasable only in a stored proc.
The trick is, to build the SQL into the variable @dynsql (
DECLARE
d variables won't work), then prepare and execute it.Now the query
Will create the output you need.