Sql server T-SQL循环中的多个自联接
我有一个表,它在一列中包含一组字段,我试图将其构造为自己行中每个字段的正确视图,如以下示例所示:Sql server T-SQL循环中的多个自联接,sql-server,tsql,while-loop,self-join,Sql Server,Tsql,While Loop,Self Join,我有一个表,它在一列中包含一组字段,我试图将其构造为自己行中每个字段的正确视图,如以下示例所示: T_data: +------+---------+---------+ | ID | Field | Value | +------+---------+---------+ | 1 | Name | John | | 1 | Age | 41 | | 1 | Height | 181 | | 2
T_data:
+------+---------+---------+
| ID | Field | Value |
+------+---------+---------+
| 1 | Name | John |
| 1 | Age | 41 |
| 1 | Height | 181 |
| 2 | Name | Kelly |
| 2 | Age | 42 |
| 2 | Height | 165 |
| 3 | Name | Dan |
| 3 | Age | 43 |
| 3 | Height | 169 |
+------+---------+---------+
T_result:
+--------+--------+--------+--------+
| Name | John | Kelly | Dan |
| Age | 41 | 42 | 43 |
| Height | 181 | 165 | 169 |
+--------+--------+--------+--------+
在同一个表上有3个自连接的示例中,我知道如何做到这一点,但这只是一个简化的示例,我的数据将有未知数量的ID和字段-我需要以某种方式循环它们,并将它们连接到一个动态表中。
我怎样才能达到我的目标呢
这是我心目中不起作用的:
with #T_id as (
select distinct ID, row_number() over (order by ID asc) as rn form T_data )
-- here's where I need to loop through the IDs
-- Pseudo-code ... I know the following doesn't work
while @i <= (select count(*) from #T_id)
begin
select T_data.Field, T_data.Value from T_data
left join T_result on T_data.Field = T_result.Field
where T_data.ID = (select ID from #T_id where rn = @i)
end
编辑:最终结果用于报表服务器使用的存储过程
任何帮助都将不胜感激:PIVOT非常好,但我使用了一个用于动态PIVOT的存储过程
Exec [prc-Pivot] 'YourTable','ID','max(Value)[]','Field','count(*)[Records]'
返回
Field Records 1 2 3
Age 3 41 42 43
Height 3 181 165 169
Name 3 John Kelly Dan
存储过程
CREATE PROCEDURE [dbo].[prc-Pivot] (
@Source varchar(1000), -- Any Table or Select Statement
@PvotCol varchar(250), -- Field name or expression ie. Month(Date)
@Summaries varchar(250), -- aggfunction(aggValue)[optionalTitle]
@GroupBy varchar(250), -- Optional additional Group By
@OtherCols varchar(500) ) -- Optional Group By or aggregates
AS
--Exec [prc-Pivot] 'Select Year=Year(TR_Date),* From [Chinrus-Series].[dbo].[DS_Treasury_Rates]','''Q''+DateName(QQ,TR_Date)','avg(TR_Y10)[-Avg]','Year','count(*)[Records],min(TR_Y10)[Min],max(TR_Y10)[Max],Avg(TR_Y10)[Avg]'
--Exec [prc-Pivot] '#Temp','Attribute','max(Description)[]','ID','count(*)[Records]'
Set NoCount On
Set Ansi_Warnings Off
Declare @Vals varchar(max),@SQL varchar(max);
Set @Vals = ''
Set @OtherCols= IsNull(', ' + @OtherCols,'')
Set @Source = case when @Source Like 'Select%' then @Source else 'Select * From '+@Source end
Create Table #TempPvot (Pvot varchar(100))
Insert Into #TempPvot
Exec ('Select Distinct Convert(varchar(100),' + @PvotCol + ') as Pvot FROM (' + @Source + ') A')
Select @Vals = @Vals + ', isnull(' + Replace(Replace(@Summaries,'(','(CASE WHEN ' + @PvotCol + '=''' + Pvot + ''' THEN '),')[', ' END),0) As [' + Pvot ) From #TempPvot Order by Pvot
Drop Table #TempPvot
Set @SQL = Replace('Select ' + Isnull(@GroupBy,'') + @OtherCols + @Vals + ' From (' + @Source + ') PvtFinal ' + case when Isnull(@GroupBy,'')<>'' then 'Group By ' + @GroupBy + ' Order by ' + @GroupBy else '' end,'Select , ','Select ')
--Print @SQL
Exec (@SQL)
Set NoCount Off
Set Ansi_Warnings on
PIVOT+动态SQL:
CREATE PROCEDURE dbo.ProcedureName
AS
BEGIN
SET NOCOUNT ON;
DECLARE @cols nvarchar(max),
@sql nvarchar(max)
SELECT @cols =COALESCE(@cols,'') +','+ QUOTENAME(ID) --,[1],[2],[3]
FROM T_data
GROUP BY ID
SET @sql = N'
SELECT *
FROM T_data
PIVOT (
MAX([Value]) FOR ID IN ('+STUFF(@cols,1,1,'')+')
) as dd'
EXEC sp_executesql @sql
END
输出:
Field 1 2 3
-------------------------------
Age 41 42 43
Height 181 165 169
Name John Kelly Dan
谷歌“sql server中的动态轴心”。这应该让您开始了。听起来您正试图生成SQL以从表中读取无限数量的属性-是否要使用SQL生成此SQL您可以在SQL中生成SQL,然后执行SQL,还是要用编程语言生成SQL命令?另一种方法是创建一个循环或游标,用于读取数据、插入到临时表中,然后最终查询临时表。或者你正在寻找一个透视表,如果你能做到这一点,它看起来是最好的