在一个语句中根据两个连接的列值选择行 - ORACLE

时间:2013-11-11 05:49:47

标签: sql oracle

首先,我不确定标题是否代表最佳问题。欢迎任何更好的建议。我的问题是我有下表:

+----+----------+-------+-----------------+
| ID | SUPPLIER | BUYER | VALIDATION_CODE |
+----+----------+-------+-----------------+
|  1 | A        | Z     |       937886521 |
|  2 | A        | X     |       937886521 |
|  3 | B        | Z     |       145410916 |
|  4 | C        | V     |      775709785  |
+----+----------+-------+-----------------+

我需要显示有BUYER Z,X的供应商A和B.然而,我希望这个条件是一对一关系而不是一对多< / strong>即可。也就是说,对于供应商A,我想显示ID为1,2的列。对于供应商B,我只想显示第3列。以下脚本将向供应商A显示所有可能的买家(我不想要):

SELECT *   
FROM   validation   
WHERE  supplier IN ( 'A', 'B' )   
       AND buyer IN ( 'X', 'Z');

这将显示以下对:(A,Z),(A,X),(B,Z)。我只需要在一个语句中显示以下内容:(A,X)(B,Z)。

期望的结果应该是这样的:

+----+----------+-------+-----------------+
| ID | SUPPLIER | BUYER | VALIDATION_CODE |
+----+----------+-------+-----------------+
|  2 | A        | X     |       937886521 |
|  3 | B        | Z     |       145410916 |
+----+----------+-------+-----------------+

4 个答案:

答案 0 :(得分:2)

您可以更新WHERE子句以过滤所需的对:

select *
from sample
where (upper(supplier),upper(buyer))
in (('A','X'),('A','Y'),('A','Z'),('B','X'),('B','Y'),('B','Z'));

我根据您的大小写示例使用了UPPER函数。

答案 1 :(得分:0)

看看你是否需要:

SELECT MAX(id),
       supplier, 
       MAX(buyer), 
       MAX(validation_code)
FROM
(SELECT *
 FROM Validation
 WHERE supplier IN ( 'A', 'B' ) AND buyer IN ( 'X', 'Z')
) filtered
GROUP BY supplier;

SQL Fiddle

我使用GROUP BY supplier 展平表格,并包含IDBuyer和{{1}的最大值}。

答案 2 :(得分:0)

或者,你可以试试这个:

SELECT id
     , supplier
     , buyer
     , validation_code 
FROM (SELECT id
             ,max(id) OVER(PARTITION BY supplier) AS maxid
             ,supplier
             ,buyer
             ,validation_code
              FROM sample) AS x
WHERE x.id=x.maxid

您可以查看内部SQL语句的结果,看看它的作用。

答案 3 :(得分:0)

尝试此查询:

select ID,SUPPLIER,BUYER,VALIDATION_CODE from
(select
t2.*,t1.counter
from
validation t2,
(select supplier,count(supplier) as counter from hatest group by supplier)t1
where 
t1.supplier = t2.supplier)t3
where t3.supplier in('A','B') and
id = case when t3.counter > 1 then 
(select max(id) from validation t4 where t4.supplier = t3.supplier) else t3.id end;