/ / Query con righe in colonne - sql, sql-server, sql-server-2008, pivot

Query con righe in colonne - sql, sql-server, sql-server-2008, pivot

Ho dati in tbl1:

item    date    amount
a   1   10
a   2   20
a   3   30
a   4   40
b   1   20
b   2   30
b   3   40
b   4   50
c   1   30
c   2   40
c   3   50
c   4   60

Ma ho bisogno di come sotto

item    1   2   3   4
a   10  20  30  40
b   20  30  40  50
c   30  40  50  60

risposte:

0 per risposta № 1

Puoi usare GROUP BY con l'aggregazione condizionale usando CASE come questo.

Dati di esempio

DECLARE @tbl1 TABLE (item CHAR(1),date int, amount int)
INSERT INTO @tbl1 VALUES
("a",   1,   10),
("a",   2,   20),
("a",   3,   30),
("a",   4,   40),
("b",   1,   20),
("b",   2,   30),
("b",   3,   40),
("b",   4,   50),
("c",   1,   30),
("c",   2,   40),
("c",   3,   50),
("c",   4,   60);

domanda

SELECT
item,
MAX(CASE WHEN date = 1 then amount END) as d1,
MAX(CASE WHEN date = 2 then amount END) as d2,
MAX(CASE WHEN date = 3 then amount END) as d3,
MAX(CASE WHEN date = 4 then amount END) as d4
FROM @tbl1
GROUP BY item

Produzione

item    d1  d2  d3  d4
a   10  20  30  40
b   20  30  40  50
c   30  40  50  60

modificare Se hai un numero sconosciuto di date, allora usa dynamic pivot come questo.

DECLARE @s NVARCHAR(MAX)

SELECT @s  = STUFF((SELECT DISTINCT "," + quotename(CONVERT(VARCHAR(10),date),"[")
FROM #tbl1 for xml path("")),1,1,"")

SET @s = N"SELECT item," + @s + " FROM #tbl1 PIVOT(MAX(amount) FOR date in(" + @s + ")) as pvt"
print @s
EXEC sp_executeSQL @s

2 per risposta № 2

Uso PIVOT

SELECT item, [1], [2], [3], [4]
FROM tbl1 t
PIVOT (SUM(amount) FOR date IN ([1], [2], [3], [4])) p
SELECT item, [10], [20], [30], [40], [50], [60]
FROM tbl1 t
PIVOT (MAX(date) FOR amount IN ([10], [20], [30], [40], [50], [60])) p

PRODUZIONE:

item    1   2   3   4
a       10  20  30  40
b       20  30  40  50
c       30  40  50  60

SQL Fiddle: http://sqlfiddle.com/#!3/f097d/12/0


0 per risposta № 3

USO PIVOT

usa il concetto pivot converti i valori di riga come intestazione di colonna

PIVOT è uno dei nuovi operatori relazionali introdotti in Sql Server 2005. Fornisce un meccanismo semplice in Sql Server per trasformare le righe in colonne.

select * from tbl1 pivot(sum(amount) for [date] in([1],[2],[3],[4])) as a