2014-02-07 87 views
0

我有三個查詢都返回1行和1列。我想將它作爲1行和3列返回。將三個查詢合併爲單個結果

我的查詢

select count(distinct rt) from gpstable where rt > GETDATE() - '1 day'::INTERVAL AND di like 'i'; 
select count(distinct rt) as count from gpstable where rt > GETDATE() - '1 day'::INTERVAL group by di order by count limit 1; 
select count(distinct rt) as count from gpstable where rt > GETDATE() - '1 day'::INTERVAL group by di order by count DESC limit 1; 

這是我曾嘗試

select userCount, min, max 
from 
(select count(distinct rt) as userCount from gpstablev2 where rt > GETDATE() - '1 day'::INTERVAL AND di like 'UmTqUo1MQU8FgXfXXGNFh7vZnQN+bt2ThIQIDHNnmWU=') as userCount, 
(select count(distinct rt) as min from gpstablev2 where rt > GETDATE() - '1 day'::INTERVAL group by di order by count limit 1) as min, 
(select count(distinct rt) as max from gpstablev2 where rt > GETDATE() - '1 day'::INTERVAL group by di order by count DESC limit 1) as max; 

而且我得到以下錯誤錯誤:列 「計數」 不gpstablev2存在[SQL狀態= 42703]

回答

3

您已經關閉了,您只需要將單個語句放入select列表中,而不是from

select (select count(distinct rt) from gpstable where rt > GETDATE() - '1 day'::INTERVAL AND di = 'i') as user_count, 
     (select count(distinct rt) from gpstable where rt > GETDATE() - '1 day'::INTERVAL group by di order by count limit 1) as min_count, 
     (select count(distinct rt) from gpstable where rt > GETDATE() - '1 day'::INTERVAL group by di order by count DESC limit 1) as max_ount; 

但我認爲這可以簡化並降低到在桌子上一個查詢:

select max(case when di = 'i' then di_count end) as user_count, 
     min(di_count) as min_count, 
     max(di_count) as max_count 
from (
    select di, 
      count(distinct rt) as di_count 
    from gpstable 
    where rt > current_date - interval '1' day 
    group by di 
)t ; 

這隻需要通過表一次,而是三次在你嘗試。這將會更有效率。我只在一個非常小的數據集上測試過,所以可能是我錯過了一些東西。

我使用了ANSI SQL格式,因爲我喜歡的標準語法,每當有一個等效的版本(這也是爲什麼我用current_date代替getdate()以指定的時間間隔interval '1' day。對於「一天」的時間本就沒有實際因爲默認的單位是一天,所以current_date - 1也可以工作。

+0

所以我不知道爲什麼,也許是因爲我使用AWS Redshift和只是一個PSQL數據庫。但是你的「current_date - interval '1'一天'導致執行時間增加到約15secs,其中「GETDATE() - '1天':: INTERVAL」保持執行時間低於1秒。不確定是否有某種緩存正在進行... –

+0

@ djc391:謝謝你的反饋,這是真的很奇怪,我從來沒有使用「普通」Postgres版本觀察到這種差異。那麼'current_date - 1'呢? –