将列分成 3 个
注意:尝试了下面的几个答案(它在 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
(为了理解而进行了大量编辑)
Note: Tried a couple of the answers below (its in Teradata, so some of the answers are giving me syntax errors everywhere)
I hit a brick wall here.
I want to compare year by year in different columns
ID, Year, Revenue
1, 2009, 10
1, 2009, 20
1, 2010, 20
2, 2009, 5
2, 2010, 50
2, 2010, 1
How do I separate it by both ID and Year?
At the end I would like it to look like this
ID, Year, Sum
1, 2009, 30
1, 2009, 20
...
2, 2010, 51
(heavily edited for comprehension)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我能为您提供的最好的详细信息是将您的表分解为子查询:
如果我们知道您正在使用哪种类型的数据库、表的真实结构是什么等,则可以提供更多详细信息,但是也许这会让你开始。
The best I can give you with the amount of detail you have provided is to break your table into subqueries:
More detail could be given if we knew which type of database you are using, what the real structure of your table is, etc. but perhaps this will get you started.
像这样的东西:
something like this:
您很可能必须进行自连接
。 someID 不一定必须是 ID,甚至不一定是索引列,但它应该是您要跨年比较的列。
例如,一个名为“Products”的表,其列/字段
您可以这样做:
如果 ProductName 是主键或索引列,则速度会更快。这也比使用嵌套选择更快,嵌套选择比联接慢得多(当联接索引时)。
You will most likely have to do a self-join
In the someID would not necessarily have to be an ID, or even an indexed column, but it should be the column you are looking to compare across the years.
E.g. a table called 'Products' with columns/fields
You could do:
This would be faster is ProductName was a primary key or an indexed column. This would also be faster than using nested selects which are much much slower than joins (when joining on an index).
根据您的数据和所需的输出,我认为您只是想要这样:
更新
现在,如果您的第一个数据样本已经是
SELECT
查询,您需要:By your data and your desired output, I think you simply want this:
Update
Now, if your first data sample is already a
SELECT
query, you need to:这看起来是 ROLLUP 命令的一个很好的候选者。它将为您提供分组依据列的自动求和:
更多信息请点击此处。
This looks like a good candidate for the ROLLUP command. It will give you automatic sums for the grouped-by columns:
More info here.