【问题标题】:Postgre SQL min/max inside THEN clauseTHEN子句中的Postgresql min/max
【发布时间】:2020-08-03 07:04:24
【问题描述】:

这是我的代码:

INSERT INTO salaries (num)
SELECT
CASE random()<0.5 WHEN true THEN min(8+floor(random()*4),10))
WHEN false THEN max(8-floor(random()*4),1)) END AS num
FROM generate_series(1,1) as seq(my_id);

返回此错误:

LINE 3: CASE random() < 0.5 WHEN true THEN (SELECT min(8+floor(rando...
                                                   ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

你能给我任何提示或者我做错了什么吗?

【问题讨论】:

    标签: sql postgresql select random sql-insert


    【解决方案1】:

    您的直接问题是您需要 least()greatst() 而不是 min()max() - 后者是聚合函数,它对集合而不是值列表进行操作。

    但我也认为您的查询没有达到您想要的效果。 random() 每次调用时都会重新计算。据推测,您希望在 case 表达式中具有一致的值,例如:

    insert into salaries (num)
    select case when rnd < 0.5  
        then least(8 + floor(rnd * 4), 10)
        else greatest(8 - floor(rnd * 4), 1) 
    end 
    from (select my_id, random() rnd from generate_series(1,1) as seq(my_id)) t
    

    仍然不清楚generate_series() 的查询目的是什么,但我认为这是过度简化查询的副作用...

    【讨论】:

      猜你喜欢
      • 2019-09-28
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多