如何将此表的行转换为列

时间:2016-02-14 16:39:46

标签: sql-server sql-server-2008 tsql pivot

如何将行转换为列?

CREATE TABLE [dbo].[Table_1]
(
     [Bill_ID]      [VARCHAR](20) NOT NULL,
     [Customer_ID]  [VARCHAR](20) NOT NULL,
     [Bill_date]    [DATE] NOT NULL,
     [Bill_Amount]  [VARCHAR](20) NOT NULL,
     [Bill_Tax]     [VARCHAR](20) NULL,
     [Create_By]    [VARCHAR](20) NOT NULL,
     [Created_Date] [DATE] NOT NULL
)
ON [PRIMARY]

SELECT [Bill_ID],
       [Customer_ID],
       [Year],
       [Bill_Amount],
       [Bill_Tax],
       [Create_By],
       [Created_Date]
FROM   (
        SELECT [Bill_ID],
               [Customer_ID],
               Datename(month, CONVERT(DATE, [Bill_date]))  AS 'Month Name',
               Datename(year, CONVERT( DATE, '2016-03-14')) AS 'Year',
               [Bill_Amount],
               [Bill_Tax],
               [Create_By],
               [Created_Date]
        FROM   [Table_1]) AS table2 PIVOT( Sum([Bill_Amount]) FOR
 (
        SELECT datename(month, CONVERT(date, [Bill_date])) AS 'Month Name') IN (January, February, March, April, May, June, July, August, September, Octobor, November, December))) 

1 个答案:

答案 0 :(得分:0)

INSERT INTO dbo.Table_1(Bill_ID,Customer_ID,Bill_date,Bill_Amount,Bill_Tax,Create_By,Created_Date)
VALUES(1,1,'20160101',1,1,1,'20160101');

SELECT *
FROM   (
            SELECT [Bill_ID],
                   [Customer_ID],
                   Datename(month, CONVERT(DATE, [Bill_date]))  AS [Month Name],
                   Datename(year, CONVERT( DATE, '2016-03-14')) AS [Year],
                   CAST([Bill_Amount] AS DECIMAL(28,2)) AS [Bill_Amount],
                   [Bill_Tax],
                   [Create_By],
                   [Created_Date]
            FROM   [Table_1]
        ) AS table2 
        PIVOT( 
            Sum([Bill_Amount]) FOR
            [Month Name] IN (January, February, March, April, May, June, July, August, September, October, November, December)
        ) AS p

结果:

+---------+-------------+------+----------+-----------+--------------+---------+----------+-------+-------+------+------+------+--------+-----------+---------+----------+----------+
| Bill_ID | Customer_ID | Year | Bill_Tax | Create_By | Created_Date | January | February | March | April | May  | June | July | August | September | Octobor | November | December |
+---------+-------------+------+----------+-----------+--------------+---------+----------+-------+-------+------+------+------+--------+-----------+---------+----------+----------+
|       1 |           1 | 2016 |        1 |         1 | 2016-01-01   | 1.00    | NULL     | NULL  | NULL  | NULL | NULL | NULL | NULL   | NULL      | NULL    | NULL     | NULL     |
+---------+-------------+------+----------+-----------+--------------+---------+----------+-------+-------+------+------+------+--------+-----------+---------+----------+----------+

注意:

VARCHAR列中存储数字是个坏主意。最好使用合适的类型,例如INTDECIMALFLOAT。因此,在对CAST进行任何操作之前,您需要VARCHAR这些SUM列到适当的类型。