按年份和行业计算市场资本总和

时间:2014-01-08 09:22:16

标签: sql oracle count sum

您好我有下表。从1到6,它每年有6个新代码。我需要计算6个新代码的每年市场资本  `1832年新代码1总和6502500新代码2 Sum = 236598 ....'

enter image description here

2 个答案:

答案 0 :(得分:1)

从我如何阅读你的问题,你想要7列; YEAR, SUM1, SUM2, SUM3, SUM4, SUM5, SUM6

SELECT
  YEAR,
  SUM(CASE WHEN NEWCODE = 1 THEN MARKETCAPITAL ELSE 0 END)  AS SUM1,
  SUM(CASE WHEN NEWCODE = 2 THEN MARKETCAPITAL ELSE 0 END)  AS SUM2,
  SUM(CASE WHEN NEWCODE = 3 THEN MARKETCAPITAL ELSE 0 END)  AS SUM3,
  SUM(CASE WHEN NEWCODE = 4 THEN MARKETCAPITAL ELSE 0 END)  AS SUM4,
  SUM(CASE WHEN NEWCODE = 5 THEN MARKETCAPITAL ELSE 0 END)  AS SUM5,
  SUM(CASE WHEN NEWCODE = 6 THEN MARKETCAPITAL ELSE 0 END)  AS SUM6,
  SUM(CASE WHEN NEWCODE > 6 THEN MARKETCAPITAL ELSE 0 END)  AS SUM_ABOVE6,
  SUM(CASE WHEN NEWCODE < 1 THEN MARKETCAPITAL ELSE 0 END)  AS SUM_BELOW1
FROM
  yourTable
GROUP BY
  YEAR

我添加了2个额外字段作为完整性检查。这样您就不会丢弃数据,而是始终捕获并聚合数据。例如,在检查两个字段始终为0之后,您可以稍后将其丢弃。

然而,请谨慎使用该结构。它对于向人类的呈现很有用,但它对于进一步的数据处理是很糟糕的。如果您要在下游的任何其他查询中使用此结果,只需坚持已有的规范化结构并在其上执行简单的GROUP BY ...

SELECT
  YEAR,
  NEWCODE,
  SUM(MARKETCAPITAL)  AS MARKETCAPITAL
FROM
  yourTable
GROUP BY
  YEAR,
  NEWCODE

如果/当您添加另一个NEWCODE(不需要SUM_ABOVE6和SUM_BELOW0作为保护)时,此规范化结构会自动适应。它使得加入数据更容易(第一种形式会使你永远谴责CASE WHEN的生活)。

答案 1 :(得分:0)

SELECT Year, Newcode, sum(MarketCapital) MarketCapital 
FROM MyTable
GROUP BY Year, Newcode