我有三个查询都返回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中不存在列“count”[SQL State = 42703]
答案 0 :(得分: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格式指定间隔interval '1' day
,因为只要有等效版本,我就更喜欢标准语法(这也是我使用current_date
代替getdate()
的原因。 “一天”的持续时间实际上并不是必需的,因为默认单位是一天,因此current_date - 1
也可以正常工作。