我有一张像
这样的表格 ID | TableID | FieldNames | Values
1 | 1 | FirstName | Value 1
2 | 1 | LastName | Value 2
3 | 1 | City | Value 3
4 | 2 | FirstName | Value 4
5 | 2 | LastName | Value 5
6 | 2 | City | Value 6
我需要在下面的网格中显示它
TableID | FirstName | LastName | City
1 | Value1 | Value2 | Value3
2 | Value4 | Value5 | value6
我知道PIVOT的概念将有助于在MS SQL中实现这一点。但是我需要在Sybase中实现它。字段名称不固定。
答案 0 :(得分:0)
进行三方自我加入:
SELECT t1.Value as FirstName, t2.Value as LastName, t3.Value as City
FROM t t1, t t2, t t3
WHERE t1.ID + 1 = t2.ID
AND t1.ID +2 = t3.ID
答案 1 :(得分:0)
在各种帖子的帮助下,我发现我可以使用动态案例陈述来做到这一点,如下所示。
DECLARE @query VARCHAR(800)
DECLARE @fieldName VARCHAR(255)
DECLARE @LoopCounter INT, @MaxCount INT
SET @query = 'select f.tableID, '
SET @fieldName = ''
SET @LoopCounter = 1
SET @MaxCount = (SELECT COUNT(DISTINCT FieldNames) FROM dbo.Table1)
WHILE (@LoopCounter <= @MaxCount)
BEGIN
SET @fieldName = (SELECT FieldNames FROM dbo.table1 WHERE ID= @LoopCounter)
SET @query = @query + ' max(case when f.FieldNames = ''' + @fieldName +''' then f.[Values] end) AS ''' + @fieldName + ''''
IF(@LoopCounter < @MaxCount)
BEGIN
SET @query = @query + ', '
END
SET @LoopCounter = @LoopCounter + 1
END
SET @query = @query + ' FROM dbo.table1 f GROUP BY f.TableID'
exec (@query)