拆分列3

时间:2011-06-23 19:31:09

标签: sql select teradata

注意:尝试了以下几个答案(在Teradata中,因此一些答案在任何地方都给出了语法错误)

我在这里碰了一堵砖墙。 我想在不同的栏目中逐年比较

ID, Year, Revenue 
1, 2009, 10 
1, 2009, 20 
1, 2010, 20 
2, 2009, 5 
2, 2010, 50
2, 2010, 1

如何将ID和年份分开?

最后我希望它看起来像这样

ID, Year, Sum
1, 2009, 30
1, 2009, 20
...
2, 2010, 51

(为了理解而进行了大量编辑)

5 个答案:

答案 0 :(得分:1)

我能为您提供的最佳细节就是将您的桌子分成子查询:

select t1.yr - t2.yr from 
 (select yr 
   from the_table where yr = 2010) t1, 
 (select yr 
   from the_table where yr = 2010) t2

如果我们知道您正在使用哪种类型的数据库,您的表的真实结构是什么等等,可以给出更多详细信息,但这可能会让您开始。

答案 1 :(得分:1)

类似的东西:

select id, t2009.year, t.2010.year, t2010.year-t.2009.year diff
from
( select id, year
from mytable
where year = 2009
) t2009
,
( select id, year
from mytable
where year = 2010
) t2010

答案 2 :(得分:0)

您很可能必须进行自我加入

SELECT [what you are comparing] FROM [table] t1
  [INNER/LEFT] JOIN [table] t2 ON t1.[someID] = t2.[someID]
WHERE t1.year = 2009 AND t2.year = 2010

在someID中,不一定必须是ID,甚至是索引列,但它应该是您希望多年来比较的列。

E.g。一个名为'Products'的表,其中包含列/字段

  • ID
  • ProductName
  • 价格

你可以这样做:

SELECT t1.ProductName, (t2.Price - t1.Price) As Price_change FROM Products t1
  INNER JOIN Products t2 ON t1.ProductName = t2.ProductName
WHERE t1.year = 2009 AND t2.year = 2010

这会更快,因为ProductName是主键或索引列。这也比使用嵌套选择更快,嵌套选择比连接慢得多(加入索引时)。

答案 3 :(得分:0)

根据您的数据和您想要的输出,我想您只是想要这个:

select ID, Year, SUM(Revenue)
from YourTable
GROUP BY ID, Year

<强>更新

现在,如果您的第一个数据样本已经是SELECT查询,则需要:

select ID, Year, SUM(Revenue)
from (SELECT...) YourSelect
GROUP BY ID, Year

答案 4 :(得分:0)

这看起来像是ROLLUP命令的一个很好的候选者。它将为您提供分组依据列的自动总和:

GROUP BY ROLLUP (ID,Year)

More info here.