SQL。可能吗?

时间:2012-08-08 08:26:59

标签: sql oracle

Oracle

从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      |

是否可以做这样的事情。

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

2 个答案:

答案 0 :(得分: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方法的技巧。通常,这些技巧并不比我在这里建议的快得多。这意味着,您将始终需要预见,您希望作为列支持多少年,并相应地调整您的查询

答案 1 :(得分:1)

在SQL服务器中尝试PIVOT

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

<强> EDIT1

如果您的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)