2016-02-14 51 views
-1

如何將行轉換爲列?如何將此列的行轉換爲列

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

回答

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列數。最好使用合適的類型,如INT,DECIMALFLOAT。因此,您需要將CAST這些VARCHAR列設置爲適當的類型,然後才能對其執行任何操作,如SUM