如何将表行转换为特定的格式组

时间:2013-01-11 06:28:38

标签: sql sql-server

我有一张桌子,我想以2种格式输出记录。

在第一个输出中,我希望表格行显示为您可以在图像中看到的左右组。 在第二个输出中,我希望行为左和右一行。

我正在使用SQL Server。

 description 1

enter image description here

enter image description here

我尝试使用数据透视但未成功。

1 个答案:

答案 0 :(得分:2)

如果你必须在T-SQL中做这样的事情,这是一种做法......

----------------------------
--  Display 1
----------------------------
DECLARE @ColBreak INT = 5
;WITH MyTable (SrNo, ItemNo, Qty) AS
(
    SELECT 1, 'A1', 150 UNION ALL
    SELECT 2, 'A2', 100 UNION ALL
    SELECT 3, 'A3', 300 UNION ALL
    SELECT 4, 'A4', 150 UNION ALL
    SELECT 5, 'A5', 100 UNION ALL
    SELECT 6, 'A6', 300 UNION ALL
    SELECT 7, 'A7', 150 UNION ALL
    SELECT 8, 'A8', 100 UNION ALL
    SELECT 9, 'A9', 300 UNION ALL
    SELECT 10, 'A10', 150
)
,Column1 AS
(
    SELECT *
    FROM MyTable T1
    WHERE SrNo  <= @ColBreak
)
,Column2 AS
(
    SELECT *
    FROM MyTable T1
    WHERE SrNo  > @ColBreak
)
SELECT *
FROM Column1 T1
JOIN Column2 T2 ON T1.SrNo + @ColBreak = T2.SrNo

----------------------------
--  Display 2
----------------------------

;WITH MyTable (SrNo, ItemNo, Qty) AS
(
    SELECT 1, 'A1', 150 UNION ALL
    SELECT 2, 'A2', 100 UNION ALL
    SELECT 3, 'A3', 300 UNION ALL
    SELECT 4, 'A4', 150 UNION ALL
    SELECT 5, 'A5', 100 UNION ALL
    SELECT 6, 'A6', 300 UNION ALL
    SELECT 7, 'A7', 150 UNION ALL
    SELECT 8, 'A8', 100 UNION ALL
    SELECT 9, 'A9', 300 UNION ALL
    SELECT 10, 'A10', 150
)
SELECT *
FROM MyTable T1
JOIN MyTable T2 ON T1.SrNo + 1 = T2.SrNo
WHERE T1.SrNo % 2 != 0