分为两列

时间:2015-01-31 07:37:51

标签: sql mysqli group-by

我正在尝试使用group by在子查询中编写查询,我引用了很多博客,但无法获得所有值。

我有三个表,下面是这些表的结构。

Pet_Seller_Master

ps_id   ps_name city_id                         
2       abc     1                               
3       xyz     2                               
4       fer     4                               
5       bbb     1                               

City_Master

city_id city_name     
1       Bangalore    
2       COIMBATORE   
4       MYSORE       

Api_Entry

api_id   ps_id otp
1        2     yes
2        3  
3        2     yes
4        3     yes
5        4           
6        5     yes
7        5     yes      
8        5     yes

查询是获取卖家数量,零otp的宠物卖家,1 otp的宠物卖家,2 otp的宠物卖家的数量,特定城市和日期的otp> 2的宠物卖家的数量范围。

通过以下查询,我可以获得city,psp和zero otp

select cm.city_name,
     count(ps.ps_id) as PSP,
     ((select count(ps1.ps_id) 
          FROM ps_master ps1  
          WHERE ps1.city = cm.city_id)-
       (SELECT count(distinct ps1.ps_id) 
          from ps_master ps1  
          INNER JOIN api_entry ae ON ps1.ps_id = ae.ps_id  and otp!=''
          WHERE ps1.city = cm.city_id  and date(timestamp) >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY AND date(timestamp) < curdate())) as zero_psp 
  from ps_master ps INNER JOIN city_master cm ON ps.city = cm.city_id and                    cm.city_type = 'IN HOUSE PNS'
   group by city_id

请告诉我解决此查询的解决方案。 提前致谢

1 个答案:

答案 0 :(得分:0)

这并不难做到,你走在正确的轨道上。以下是我要使用的内容:

select c.city_name, a.otp, p.ps_name, COUNT(*) nbr
from Api_Entry a
inner join Pet_Seller_Master p on p.ps_id=a.ps_id
inner join City_Master c on p.city_id=c.city_id
group by c.city_name, a.otp, p.ps_name

现在,如果您想获得零otp的卖家数量,您只需应用where子句:

where otp <> 'yes'

如果您想获得otp> 2的宠物卖家数量,那么您只需使用子查询:

select * 
from (
    select c.city_name, a.otp, p.ps_name, COUNT(*) nbr
    from #tempA a
    inner join #tempP p on p.ps_id=a.ps_id
    inner join #tempC c on p.city_id=c.city_id
    group by c.city_name, a.otp, p.ps_name
) g
where nbr > 2