0

我有一个数据如下:

桌子


country     date                value       
------------------------------------------------------
test1       5/1/2008            500
test1       5/7/2008            200 
test1       5/8/2008            300
test1       7/1/2008            100
test1       7/2/2008            100
test2       6/1/2008            100

我想要一个如下的结果:

 Result
-----------
countryName          May-08         Jun-08      July-08
test1                1000             -          200
test2                 -              100 
4

2 回答 2

1

这是改编自T-SQL Pivot?从行值创建表列的可能性

你可以看到它在这里工作:http ://sqlfiddle.com/#!3/7b8c0/28

我认为您可能需要摆弄列顺序

-- Static PIVOT
SELECT *
FROM (SELECT country,
      CONVERT(char(3), date, 0) + '-' +  
      RIGHT(CONVERT(varchar, YEAR(date)), 2) AS date,
      value
FROM country) AS D
PIVOT(SUM(value) FOR date IN([May-08],[Jun-08],[Jul-08])) AS P;
GO

-- Dynamic PIVOT
DECLARE @T AS TABLE(y INT NOT NULL PRIMARY KEY);

DECLARE 
@cols AS NVARCHAR(MAX),
@y    AS INT,
@sql  AS NVARCHAR(MAX)

SELECT @cols = STUFF(
(SELECT N',' + QUOTENAME(y) AS [text()]
FROM (SELECT DISTINCT CONVERT(char(3), date, 0) + '-' +  
      RIGHT(CONVERT(varchar, YEAR(date)), 2) AS y 
      FROM Country
     ) AS Y
ORDER BY y desc
FOR XML PATH('')),
1, 1, N'')

-- Construct the full T-SQL statement
-- and execute dynamically
SET @sql = N'SELECT *
FROM (SELECT country, CONVERT(char(3), date, 0) + ''-'' +  
      RIGHT(CONVERT(varchar, YEAR(date)), 2) AS date, value
FROM Country) AS D
PIVOT(SUM(value) FOR date IN(' + @cols + N')) AS P;'

EXEC sp_executesql @sql
于 2013-02-26T12:02:44.100 回答
0

您必须为此使用相当复杂的查询,使用LOOP它认为。

要创建动态列名,请查看这篇文章:https ://stackoverflow.com/a/10926106/1321564

使用 sql server 你有一些优势:https ://stackoverflow.com/a/5638042/1321564

于 2013-02-26T11:27:13.017 回答