0

Oracle

select * from table1;

column1 |     column2    |    column3   |
a       |      2010      |       1      |
a       |      2011      |       2      |
a       |      2012      |       3      |
b       |      2010      |       4      |
b       |      2011      |       5      |
b       |      2012      |       6      |
c       |      2010      |       7      |
c       |      2011      |       8      |
c       |      2012      |       9      |

Is it possible to do something like this.

column1 |    2010    |    2011    |    2012    |
a       |     1      |      2     |      3     |
b       |     4      |      5     |      6     |
c       |     7      |      8     |      9     |
4

2 回答 2

4

是的

SELECT t.column1,
       (SELECT SUM(column3) FROM table1 
        WHERE column1 = t.column1 AND column2 = 2010) AS "2010",
       (SELECT SUM(column3) FROM table1 
        WHERE column1 = t.column1 AND column2 = 2011) AS "2011",
       (SELECT SUM(column3) FROM table1 
        WHERE column1 = t.column1 AND column2 = 2012) AS "2012"
FROM (
  SELECT DISTINCT column1 FROM table1
) t
ORDER BY t.column1

请注意,我已经添加了SUM()聚合函数colum3,以防每个column1, column2.

根据您使用的数据库,以下等效查询可能会更快一些:

SELECT t.column1,
       (SELECT SUM(column3) FROM table1 
        WHERE column1 = t.column1 AND column2 = 2010) AS "2010",
       (SELECT SUM(column3) FROM table1 
        WHERE column1 = t.column1 AND column2 = 2011) AS "2011",
       (SELECT SUM(column3) FROM table1 
        WHERE column1 = t.column1 AND column2 = 2012) AS "2012"
FROM table1 t
GROUP BY t.column1
ORDER BY t.column1

请注意,您可以使用该PIVOT子句以更简洁的方式实现相同的目的(正如其他人所建议的那样)。在Oracle 11g中,这将转化为:

SELECT column1, "2010", "2011", "2012"
FROM table1
PIVOT (SUM(column3) FOR column2 IN (2010, 2011, 2012)) 

在任何情况下,我都不知道有任何数据库允许每个表表达式动态列数,而不使用涉及 XML 或其他动态 SQL 方法的技巧。通常,这些技巧并不比我在这里建议的快多少。这意味着,您将始终必须预见,您希望作为列支持多少年,并相应地调整您的查询

于 2012-08-08T08:30:50.453 回答
1

在 SQL 服务器中尝试 PIVOT

select column1  ,   [2010],[2011],[2012]
from your_table
PIVOT (MAX(column3) FOR column2 IN ([2010],[2011],[2012])) P 

编辑1

如果您的 Column2 是动态的,请尝试以下操作:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(column2) 
                    from your_table
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')



set @query = 'SELECT column1    , ' + @cols + ' from your_table
             pivot 
            (
                MAX(column3)
                for column2 in (' + @cols + ')
            ) p '
print(@query)
execute(@query)
于 2012-08-08T08:32:04.850 回答