postgresql 在UNION查询中查找MIN

6kkfgxo0  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(150)

我有一个有三列的表,Price1,Price2和Price3。对于每个价格列,还有一个专用的金额列,Amount 1,Amount 2和Amount 3。还有列ID和Batch。
我想要实现的是找到所有三个Amount列组合的最小值。
以下是我现在使用的SQL

Select
MIN(Q.Min_Size)  As Min_Min_Size 
From
    (Select
         Min("Archive"."Amount1") As Min_Size
     From
         "Archive"
     Where
         "Archive"."ID" = '123' And
         "Archive"."Price1" = 7.4 And
         "Archive"."Batch" > 2986 And
         "Archive"."Batch" < 6243) Q
Union 
Select
    Q.Min_Size
From
    (Select
         Min("Archive"."Amount2") As Min_Size
     From
         "Archive"
     Where
         "Archive"."ID" = '123' And
         "Archive"."Price2" = 7.4 And
         "Archive"."Batch" > 2986 And
         "Archive"."Batch" < 6243) Q
Group By
    Q.Min_Size
Union 
Select
    Q.Min_Size
From
    (Select
         Min("Archive"."Amount3") As Min_Size
     From
         "Archive"
     Where
         "Archive"."ID" = '123' And
         "Archive"."Price3" = 7.4 And
         "Archive"."Batch" > 2986 And
         "Archive"."Batch" < 6243) Q
Group By
    Q.Min_Size

字符串
有了这个语句,我有三行,第一行是列“Amount 1”的最小值,第二行是列“Amount 2”的最小值,第三行是列“Amount 3”的最小值。我想实现的是一行只有三行中的最小值

编辑

我发现了这个新的说法,但我想知道是否有一个更好的。

Select
    Min(Least("Archive"."Amount1", "Archive"."Amount2", "Archive"."Amount3")) As MinAmount
From
    "Archive"
Where
    ("Archive"."ID" = '123' And
        "Archive"."Price1" = 7.4 And
        "Archive"."Batch" > 2986 And
        "Archive"."Batch" < 6243) Or
    ("Archive"."ID" = '123' And
        "Archive"."Batch" > 2986 And
        "Archive"."Batch" < 6243 And
        "Archive"."Price2" = 7.4) Or
    ("Archive"."ID" = '123' And
        "Archive"."Batch" > 2986 And
        "Archive"."Batch" < 6243 And
        "Archive"."Price3" = 7.4)

sbdsn5lh

sbdsn5lh1#

有一个least()函数:demo

SELECT min(least("Archive"."Amount1", 
                 "Archive"."Amount2", 
                 "Archive"."Amount3")) AS "Min_Size"
FROM "Archive"
WHERE "Archive"."ID" = '123'
AND 7.4 IN("Archive"."Price1",
           "Archive"."Price2",
           "Archive"."Price3")
AND "Archive"."Batch" > 2986
AND "Archive"."Batch" < 6243;

字符串

相关问题