一列上的组,基于另一列中不同值的汇总计数
我有一个具有类似值的表:
CREATE TABLE myTable
(`ts` varchar(2), `usr_id` varchar(1), `data` varchar(1))
;
INSERT INTO myTable
(`ts`, `usr_id`, `data`)
VALUES
('11', 'A', 'x'),
('11', 'A', 'x'),
('11', 'B', 'x'),
('11', 'C', 'x'),
('11', 'C', 'x'),
('11', 'C', 'x'),
('22', 'B', 'x'),
('33', 'C', 'x'),
('33', 'C', 'x'),
('33', 'D', 'x'),
('33', 'A', 'x')
;
我想根据TS进行组,并显示以下usr_id的不同值的计数。
t | 的TS计数 | 11 | 计数 |
---|---|---|---|
2 | 1 | 3 | 22 |
0 | 1 | 0 | 33 |
1 | 0 | 3 | < |
a href =“ http://www.sqlfiddle.com/#!9/bbbf4fc/2” “> http://www.sqlfiddle.com/#!9/bbf4fc/2
我无法取得太大的进步通过TS进行组:从Mytable组中选择TS,USR_ID,count(*)由TS,usr_id; 但是我希望在同一行中使用A,B和其他人的行计数,无法弄清楚如何实现这一目标。
I have a table with values like so:
CREATE TABLE myTable
(`ts` varchar(2), `usr_id` varchar(1), `data` varchar(1))
;
INSERT INTO myTable
(`ts`, `usr_id`, `data`)
VALUES
('11', 'A', 'x'),
('11', 'A', 'x'),
('11', 'B', 'x'),
('11', 'C', 'x'),
('11', 'C', 'x'),
('11', 'C', 'x'),
('22', 'B', 'x'),
('33', 'C', 'x'),
('33', 'C', 'x'),
('33', 'D', 'x'),
('33', 'A', 'x')
;
I want to do a GROUP BY based on ts and display the counts for distinct values of usr_id like below.
ts | count of A | count of B | count of others |
---|---|---|---|
11 | 2 | 1 | 3 |
22 | 0 | 1 | 0 |
33 | 1 | 0 | 3 |
http://www.sqlfiddle.com/#!9/bbf4fc/2
I couldn't make much progress beyond doing the GROUP BY for ts: select ts, usr_id, count(*) from myTable group by ts, usr_id;
But I want the counts of rows with A, B and others in the same row, can't figure out how to achieve that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是您的查询
This is your query
Demo
PostgreSQL允许过滤聚合:
db&lt;&gt; fiddle 此处
PostgreSQL allows filtering aggregates:
db<>fiddle here
您的示例链接是ybout mysql,但是
sample
和posdgres
请参见示例
your sample link is ybout mysql, but
Sample
And for posdgres
see example