SQL 按一列分组,计算另一列中的条目数
我正在使用 sqlite3 数据库,带有这样的表。
|name |action |
-------------------------
|john |run |
|jim |run |
|john |run |
|john |jump |
|jim |jump |
|jim |jump |
|jim |dive |
我想要得到这样的输出
|name |run |jump |dive |
---------------------------------
|john |2 |1 |0 |
|jim |1 |2 |1 |
我最接近的是这个,但我想要像上面这样的单行。
SELECT name, action, COUNT(name)
FROM table
GROUP BY name, action
|name |action |COUNT(name) |
|john |run |2 |
|john |jump |1 |
|jim |run |1 |
|jim |jump |2 |
|jim |dive |1 |
另外,我还需要在查询中包含一些 WHERE 语句。
我晚上睡觉时是否认为这会起作用?
I'm using a sqlite3 database, with a table like this.
|name |action |
-------------------------
|john |run |
|jim |run |
|john |run |
|john |jump |
|jim |jump |
|jim |jump |
|jim |dive |
I want to get an output like this
|name |run |jump |dive |
---------------------------------
|john |2 |1 |0 |
|jim |1 |2 |1 |
The closest I've come is with this, but I would like to have a single row like above.
SELECT name, action, COUNT(name)
FROM table
GROUP BY name, action
|name |action |COUNT(name) |
|john |run |2 |
|john |jump |1 |
|jim |run |1 |
|jim |jump |2 |
|jim |dive |1 |
Also, I will need to have some WHERE statements in the query as well.
Am I up in the night thinking this will work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您还可以通过使用总和聚合和 CASE 条件来完成您想要的操作,如下所示:
每次添加其他操作时,您仍然需要更改查询。
You can also accomplish what you want by using a sum aggregate and CASE conditions like this:
You will still have to change the query every time additional actions are added.
您想要做的事情称为交叉制表。通常,这在 Excel 和其他电子表格软件中作为称为数据透视表的功能提供。
我找到了一篇博客文章,它将帮助您使用 SQL 来完成此操作。查看 pivot-table-hack-in -sqlite3-和-mysql
What you are trying to do is called cross tabulation. Normally this is available as a feature called pivot table in Excel and other spreadsheet softwares.
I have found a blog article which will help you with this using SQL. Check out pivot-table-hack-in-sqlite3-and-mysql
我不太了解 SQLLite,但我想象您可以使用子查询或临时表。
使用 mssql,您可以编写如下内容:
但是每次添加另一种操作类型时都需要重写。您可能应该添加一个索引来提高表的速度。但首先用“真实”数据检查查询计划。
I don't know SQLLite that well, but I image that you could use subqueries or temp tables.
With mssql you could write something like this:
But this would need to be rewritten every time you ad another action type. You should probably add an index to get the speed up on the table. But check the query plan with "real" data first.
在 Oracle 数据库中,您可以像下面这样编写查询来显示所需的解决方案:-
这将给出所需的输出..
in oracle database you can write like below query to show required solution :-
this will give the desired output..