SQL Server查询拆分表

时间:2013-03-05 07:02:33

标签: sql-server

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

+---------------+
| 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))

1 个答案:

答案 0 :(得分: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 Fiddle

此方法使用动态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 Fiddle

如果您不希望自动处理列,则可以使用静态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