查询以获取特定客户的数据计数以及表格中的所有其他数据

时间:2018-08-29 16:56:15

标签: sql phpmyadmin

我的表结构如下:

group_id | cust_id | ticket_num


60    |   12    |   1
60    |   12    |   2
60    |   12    |   3
60    |   12    |   4
60    |   30    |   5
60    |   30    |   6
60    |   31    |   7
60    |   31    |   8
65    |   02    |   1
  • 我想获取group_id = 60的所有数据,并找到该组中每个客户的ticket_num计数。我的输出应该是这样*

cust_id | ticket_count | ticket_num


12    |      4      |   1
12    |             |   2
12    |             |   3
12    |             |   4
30    |      2      |   5
30    |             |   6
31    |      2      |   7
31    |             |   8

我尝试了此查询

SELECT gd.cust_id, Count(gd.cust_id),gd.ticket_num 
FROM Group_details gd 
WHERE gd.group_id = 65 
GROUP BY gd.cust_id;

,但此查询不起作用。请帮助我进行查询。

感谢进阶。

2 个答案:

答案 0 :(得分:0)

使用聚合和子查询

   select t2.*,t1.ticket_num from Group_details t1
   inner join
   ( 
   SELECT gd.cust_id, Count(gd.ticket_num) as ticket_count 
   FROM Group_details gd where gd.group_id = 60 
   GROUP BY gd.cust_id 
   ) t2 on t1.cust_id=t2.cust_id

http://sqlfiddle.com/#!9/dd718b/1

答案 1 :(得分:0)

您似乎希望将ANSI / ISO标准row_number()函数和count()作为窗口函数:

select gd.cust_id, count(*) over (partition by gd.cust_id) as num_tickets,
       row_number() over (order by gd.cust_id) as ticket_seqnum
from group_details gd
where gd.group_id = 60;