如何将行转换为列?
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 :(得分: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
,DECIMAL
或FLOAT
。因此,在对CAST
进行任何操作之前,您需要VARCHAR
这些SUM
列到适当的类型。