1

不知道它是如何调用的,我需要这样做:

+---------------+
| param | value |
|   1   |   3   |
|   1   |   3   |
|   2   |   4   |
|   2   |   4   |
+-------+-------+

+-----------------+
| param1 | param2 |
|    3   |    4   |
|    3   |    4   |
+-------+---------+

没有可能INNER JOIN吗?

我的错误在哪里?

SELECT TOP 10 
    dbo.RW_ReceivedData.[Value] AS Value1, 
    dbo.RW_ReceivedData.[Value] AS Value2
FROM 
    RW_ReceivedData
WHERE 
    dbo.RW_ReceivedData.LogicalName = CAST(0x01000F0800FF AS varbinary(8000)),  
    dbo.RW_ReceivedData.LogicalName = CAST(0x01000F0800FF AS varbinary(8000))
4

1 回答 1

1

这应该有效:

DECLARE @cols NVARCHAR(4000) 
= STUFF(
    (
        SELECT  DISTINCT ',[' + CAST(param AS VARCHAR(10)) + ']'
        FROM    tbl
        FOR XML PATH('')
    ),1,1,'')

DECLARE @colNames NVARCHAR(4000) 
= STUFF(
    (
        SELECT  DISTINCT ',[' + CAST(param AS VARCHAR(10)) + '] AS param' + CAST(param AS VARCHAR(10))
        FROM    tbl
        FOR XML PATH('')
    ),1,1,'')

DECLARE @sql NVARCHAR(4000) = 
'
SELECT  '+@colNames+'
FROM    
(
    SELECT  *, ROW_NUMBER() OVER (PARTITION BY param ORDER BY param) n
    FROM    tbl
) t
PIVOT   
(
    MIN(value) FOR param IN ('+@cols+')
) pvt'

EXEC(@sql)

这是SQL 小提琴

这种方法使用动态PIVOT. 为了获得预期的结果ROW_NUMBER(),使用了分区,因为param列中的值不是唯一的。

更新

您也可以像这样尝试,但您必须手动将列添加到查询中:

SELECT  SUM(CASE WHEN param = 1 THEN value ELSE 0 END) param1
        , SUM(CASE WHEN param = 2 THEN value ELSE 0 END) param2
        , SUM(CASE WHEN param = 3 THEN value ELSE 0 END) param3
FROM
    (
        SELECT  *
                , ROW_NUMBER() OVER (PARTITION BY param ORDER BY param) num
        FROM    tbl
    ) t
GROUP BY
        num

SQL小提琴

如果您不希望自动处理列,则可以使用 static PIVOT

SELECT  [1] AS param1
        ,[2] AS param2  
FROM    (      
    SELECT  *
            , ROW_NUMBER() OVER (PARTITION BY param ORDER BY param) n      
    FROM    tbl) t  
PIVOT   (      
    MIN(value) FOR param IN ([1],[2])  
) pvt
于 2013-03-05T07:34:59.600 回答