【问题标题】:SQL decode or max with multiple rows and blank/null rows多行和空白/空行的 SQL 解码或最大值
【发布时间】:2018-01-31 19:46:56
【问题描述】:

当表格同时包含空白/空行和多行时,我试图返回 1 行。

Table1.cust(唯一) Table2.prop(3个字段创建一个具有一对多自定义的唯一ID) Table3.start(唯一的 [cust, prop and start] 一些空白/空记录存在于 cust)

问题在于解码和 table1、table2 和 table 3 连接。如果我只是与 table1 进行连接而不进行解码,我会得到额外的记录并且没有得到空记录,但是当我合并三个表时,我仍然没有得到空白/空记录。

示例代码

select table1.cust,
   table2.prop.(3 fields),
   decode(table3.startdate,' ','1901/01/01',
                            null,'1901/01/01',
                            table3.start)
from table1, table2(subquery), table3(subquery)
where table1 = table2(+)
and (table1.cust = table2.cust(+)
and table2.(3 fields) = table3.(3 fields))

返回 客户 1、道具 3、日期 3 Cust2 - 失踪 客户 3、道具 2、日期 2 Cust4, prop1, date1

示例代码

select table1.cust,
   table2.prop.(3 fields),
   decode(table3.startdate,' ','1901/01/01',
                            null,'1901/01/01',
                            table3.start)
from table1, table2(subquery), table3(subquery)
where table1 = table2(+)
and (table1.cust = table2.cust(+)
and table2.(3 fields) = table3.(3 fields))

返回

Cust1, prop1, date1 (not the last record)
Cust1, prop2, date2 (not the last record)
Cust1, prop3, date3 - Good
Cust2, prop1, date1 - Good
Cust3, prop1, date1 (not the last record)
Cust3, prop2, date2 - Good
Cust4, prop1, date1 - Good

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    我不能确定,因为我不完全理解你的写作,但问题很可能是:

    and table2.(3 fields) = table3.(3 fields))
    

    在任一侧排除 nulls(null = null 在 SQL 中不正确,因此在 where 中会导致行被排除)。

    尝试在适当的地方添加(+)(或or xxx is null)以停止排除您想要的行,或者更确切地说,放弃那种可怕、过时和令人困惑的语法并使用from table1 left join table2 on table2.f = table1.f :)

    另外,您可能想了解ternary logic

    【讨论】:

    • 你只能做一个左表连接,因为我是连接 1 到 2 和 2 到 3,所以它只允许一个连接。对不起,可怕的,过时的语法(plsql),但这是我所知道的。我有mssql的书,还没开始呢。
    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多