PostgreSQL查询未返回预期结果

时间:2018-11-14 08:59:27

标签: postgresql

我已经形成了这个PostgreSQL查询,以返回一些结果:

Select 
  TblDailyRch.viewing_date1, 
  TblDailyRch.channel_name1, 
  ((TblDailyRch.Reach/tblUniqViewers4AllChannels.ReachAll) * 100) "Reach %"
From
  (Select 
     viewing_date viewing_date1, 
     channel_name channel_name1, 
     count(distinct party_wid) Reach 
   From 
     tv_viewing_sessions_daily_aggregate 
   Where 
     viewing_date between '20171101' and '20171102' 
   Group By 
     viewing_date1, 
     channel_name 
   Order BY 
     viewing_date1, 
     channel_name1) TblDailyRch,
   (Select 
      viewing_date viewing_date2, 
      count(distinct party_wid) ReachAll 
    From 
      tv_viewing_sessions_daily_aggregate 
    Where 
      viewing_date between '20171101' and '20171102' 
    Group By 
      viewing_date2 Order BY viewing_date2) tblUniqViewers4AllChannels 
Where 
  tblUniqViewers4AllChannels.viewing_date2 = TblDailyRch.viewing_date1;

以下是仅运行第一个查询的示例结果:

 viewing_date |       channel_name       | reach
--------------+--------------------------+--------
 20171101     | 3E                       |  25133
 20171101     | 4FM                      |    253
 20171101     | 4MUSIC                   |   1243
 20171101     | 98FM                     |    236
 20171101     | ALIBI                    |   3468

以下是运行第二个查询的示例结果:

viewing_date2 | reachall
---------------+----------
 20171101      |   115623
 20171102      |   113898

但是当我运行完整的查询时,我得到以下结果:

 viewing_date |       channel_name       | Reach %
--------------+--------------------------+----------
 20171101     | 3E                       |        0
 20171101     | 4FM                      |        0
 20171101     | 4MUSIC                   |        0
 20171101     | 98FM                     |        0

从逻辑上讲,查询似乎是正确的,但是我无法弄清楚为什么在运行完整查询时,第三列“达到百分比”将结果显示为“ 0”,而不是预期的百分比计算值?

1 个答案:

答案 0 :(得分:3)

这两个COUNT()都返回整数,并且整数除法不返回小数。将其中之一强制转换为浮点将强制进行浮点除法,并返回您的期望值。

例如:

count(distinct party_wid)::float Reach