Oracle SQL Query模仿VLOOKUP功能

时间:2014-11-12 10:05:17

标签: sql oracle oracle-sqldeveloper vlookup

我试图在Oracle SQL查询中获取VLOOKUP功能。我在那里使用子查询select语句尝试了这个,但它没有返回任何值。

必需逻辑

Lookup_Link_Date字段中需要VLOOKUP逻辑,然后Same_Date字段中也使用该逻辑。

基本上在Excel中Lookup_Link_Date字段在Link_String字段中查找String字段,然后返回其旁边的date字段。

为了尝试在Oracle SQl中复制它,我创建了一个子查询选择语句,用于查找date type = type_ref AND no = no_ref,但它永远不会返回任何结果,我不知道为什么。

当前查询

SELECT DISTINCT
g.type AS Type, 
g.no AS Number,
g.date AS Date, 
g.type_ref AS Type_Ref,
g.no_ref AS No_Ref, 
g.type||g.no||g.company AS String,
g.type_ref||g.no_ref||g.company AS Link_String,
(SELECT g.date 
 FROM gtable g 
 WHERE g.type_ref = g.type 
 AND g.no_ref = g.no) AS Lookup_Link_Date,
CASE WHEN (SELECT g.date 
           FROM gtable g 
           WHERE g.type_ref = g.type 
           AND g.no_ref = g.no) = g.date 
     THEN 'YES' 
     ELSE 'NO' 
     END AS Same_Date

FROM gtable g

尝试#2查询

SELECT DISTINCT
g.type AS Type, 
g.no AS Number,
g.date AS Date, 
g.type_ref AS Type_Ref,
g.no_ref AS No_Ref, 
g.type||g.no||g.company AS String,
g.type_ref||g.no_ref||g.company AS Link_String,
(SELECT b.date 
 FROM gtable b 
 WHERE b.type_ref = b.type 
 AND b.no_ref = b.no) AS Lookup_Link_Date,
CASE WHEN (SELECT d.date 
           FROM gtable d 
           WHERE d.type_ref = d.type 
           AND d.no_ref = g.no) = d.date 
     THEN 'YES' 
     ELSE 'NO' 
     END AS Same_Date

FROM gtable g

尝试#3工作查询

SELECT DISTINCT
g.type AS Type, 
g.no AS Number,
g.date AS Date, 
g.type_ref AS Type_Ref,
g.no_ref AS No_Ref, 
g.type||g.no||g.company AS String,
g.type_ref||g.no_ref||g.company AS Link_String,
(SELECT date 
 FROM gtable 
 WHERE type_ref = g.type 
 AND no_ref = g.no) AS Lookup_Link_Date,
CASE WHEN (SELECT date 
           FROM gtable 
           WHERE type_ref = g.type 
           AND no_ref = g.no) = g.date 
     THEN 'YES' 
     ELSE 'NO' 
     END AS Same_Date

FROM gtable g

1 个答案:

答案 0 :(得分:3)

检查你的别名。无论是内部还是外部。因此,g.type_ref = g.typeg.no_ref = g.no据称不能比较您想要比较的内容。

来自马特的编辑:这是Matt为他工作的查询:

SELECT DISTINCT
g.type AS Type, 
g.no AS Number,
g.date AS Date, 
g.type_ref AS Type_Ref,
g.no_ref AS No_Ref, 
g.type||g.no||g.company AS String,
g.type_ref||g.no_ref||g.company AS Link_String,
(SELECT date 
 FROM gtable 
 WHERE type_ref = g.type 
 AND no_ref = g.no) AS Lookup_Link_Date,
CASE WHEN (SELECT date 
           FROM gtable 
           WHERE type_ref = g.type 
           AND no_ref = g.no) = g.date 
     THEN 'YES' 
     ELSE 'NO' 
     END AS Same_Date
FROM gtable g;

编辑(接受后:-)以下是如何使用自联接编写查询:

SELECT 
  g.type AS Type, 
  g.no AS Number,
  g.date AS Date, 
  g.type_ref AS Type_Ref,
  g.no_ref AS No_Ref, 
  g.type||g.no||g.company AS String,
  g.type_ref||g.no_ref||g.company AS Link_String,
  gref.date AS Lookup_Link_Date,
  CASE WHEN g.date = gref.date THEN 'YES' ELSE 'NO' END AS Same_Date
FROM gtable g
LEFT JOIN gtable gref ON g.type = gref.type_ref and g.no = gref.no_ref;

(我删除了DISTINCT。是否有重复项?然后你需要它,否则不需要。)