简单的sql:如何分组为单独的列?
假设我将股票价格保存在这样的 3 列表中:
create table stocks(
ticker text,
day int,
price int
);
insert into stocks values ('aapl', 1, 100);
insert into stocks values ('aapl', 2, 104);
insert into stocks values ('aapl', 3, 98);
insert into stocks values ('aapl', 4, 99);
insert into stocks values ('goog', 1, 401);
insert into stocks values ('goog', 2, 390);
insert into stocks values ('goog', 3, 234);
我想要的结果如下所示:
day aapl goog
1 100 401
2 104 390
3 98 234
4 99 null
我真的需要选择两次,每个股票一次,然后外部连接结果吗?
Say I keep stocks prices in a 3 column table like this:
create table stocks(
ticker text,
day int,
price int
);
insert into stocks values ('aapl', 1, 100);
insert into stocks values ('aapl', 2, 104);
insert into stocks values ('aapl', 3, 98);
insert into stocks values ('aapl', 4, 99);
insert into stocks values ('goog', 1, 401);
insert into stocks values ('goog', 2, 390);
insert into stocks values ('goog', 3, 234);
And I want results that look like:
day aapl goog
1 100 401
2 104 390
3 98 234
4 99 null
Do I really need to select twice, once for each ticker, and then outer join the results?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样:
演示
Like this:
DEMO
无论您使用什么数据库,您想要实现的概念都称为“数据透视表”。
这是 mysql 的一个例子:
http://en.wikibooks.org/wiki/MySQL/Pivot_table
一些数据库内置了有关功能,请参阅下面的链接。
SQL服务器:
http://msdn.microsoft.com/de-de/library/ms177410.aspx甲骨文
:
http://www.dba-oracle.com/t_pivot_examples.htm
您随时可以创建用手转动枢轴。只需选择结果集中的所有聚合,然后从该结果集中进行选择即可。
请注意,在您的情况下,您可以使用 concat 将所有名称放入一列中(我认为这是 mysql 中的 group_concat ),因为您无法知道有多少名称与
ticker
相关。Regardless of the database you are using, the concept of what you are trying to achieve is called "Pivot Table".
Here's an example for mysql:
http://en.wikibooks.org/wiki/MySQL/Pivot_table
Some databases have builtin features for that, see the links below.
SQLServer:
http://msdn.microsoft.com/de-de/library/ms177410.aspx
Oracle:
http://www.dba-oracle.com/t_pivot_examples.htm
You can always create a pivot by hand. Just select all the aggregations in a result set and then select from that result set.
Note, in your case, you can put all the names into one column using concat (i think that's group_concat in mysql), since you cannot know how many names are related to a
ticker
.是的,除非您的数据库具有用于旋转的 SQL 扩展。 以下是在 Microsoft SQL Server 中执行此操作的方法。
Yes you do, unless your DB has SQL extensions for pivoting. Here's how you do it in Microsoft SQL Server.