2016-04-05 10 views
-2

So transponieren Sie Zeilen und Spalten aus einer SQL-Abfrage wie folgt. SQL Server 2012 unter Verwendung einer Abfrage zu schreiben, die auch funktionieren wird als Daten in der Datenbanktabelle hinzugefügt wirdSo transponieren Sie Zeilen und Spalten aus einer SQL-Abfrage

enter image description here

+3

Zeigen Sie uns, was Ihr Wunsch-Ausgang ist und was hat Ihnen versuchen und was ist Ihre RDBMS. \t Bitte lesen Sie [** How-to-Ask **] (http://stackoverflow.com/help/how-to-ask) \t \t Und hier ist ein großartiger Ort, um [** START **] (http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/) um zu erfahren, wie Sie Ihre Fragequalität verbessern und bessere Antworten erhalten. –

Antwort

0

Try this:

SELECT * FROM t_TableName GROUP BY Month 
0

Versuchen

SQL Fiddle

MS SQL Server 2008 Schema-Setup:

CREATE TABLE yourtable 
    ( 
     [mon] varchar(3), [to] float, [aapl] float, 
     [msft] float, [ko] float 
    ) 
; 

INSERT INTO yourtable 
([mon],[to],[aapl],[msft],[ko]) 
VALUES 
    ('jan', 12.25,112.25,56.52,45), 
    ('feb', 12.52,125.25,56.87,46), 
    ('mar', 12.65,126,56.94,47), 
    ('apr', 12.95,127,56.99,45), 
    ('may', 12.85,129,57.25,44) 
; 

Abfrage 1:

select * from yourtable 

Results:

| mon | to | aapl | msft | ko | 
|-----|-------|--------|-------|----| 
| jan | 12.25 | 112.25 | 56.52 | 45 | 
| feb | 12.52 | 125.25 | 56.87 | 46 | 
| mar | 12.65 | 126 | 56.94 | 47 | 
| apr | 12.95 | 127 | 56.99 | 45 | 
| may | 12.85 | 129 | 57.25 | 44 | 

Abfrage 2:

select * 
from 
(
    select * 
    from yourtable 
    unpivot 
    (
    value 
    for month in ([to],[aapl],[msft],[ko]) 
) unpiv 
) src 
pivot 
(
    max(value) 
    for mon in (jan, feb, mar, apr, may) 
) piv 

Results:

| month | jan | feb | mar | apr | may | 
|-------|--------|--------|-------|-------|-------| 
| aapl | 112.25 | 125.25 | 126 | 127 | 129 | 
| ko |  45 |  46 | 47 | 45 | 44 | 
| msft | 56.52 | 56.87 | 56.94 | 56.99 | 57.25 | 
| to | 12.25 | 12.52 | 12.65 | 12.95 | 12.85 | 
Verwandte Themen