获取所有输入值在两列中具有相同值的行

时间:2017-10-02 14:11:22

标签: sql oracle

我有一个供应商表,其中包含列Item,suppliername和状态。对于给定的项目,我必须获取suppliername和状态列中具有相同值的行,前提是所有给定项目都存在相同的值。

例如,如果以下是表格

Item    Suppliername      Status
A        S1               Created
A        S1               Approved
B        S1               Approved
B        S2               Created
C        S1               Created
C        S1               Approved

给出的输入是项目'A','B','C'

输出应如下所示。

Suppliername      Status
S1                Approved

2 个答案:

答案 0 :(得分:0)

一些选择:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TYPE CharList IS TABLE OF CHAR(1)
/

CREATE TABLE table_name ( Item, Suppliername, Status ) AS
SELECT 'A', 'S1', 'Created' FROM DUAL UNION ALL
SELECT 'A', 'S1', 'Approved' FROM DUAL UNION ALL
SELECT 'B', 'S1', 'Approved' FROM DUAL UNION ALL
SELECT 'B', 'S2', 'Created' FROM DUAL UNION ALL
SELECT 'C', 'S1', 'Created' FROM DUAL UNION ALL
SELECT 'C', 'S1', 'Approved' FROM DUAL
/

查询1

SELECT Suppliername, Status
FROM   table_name
GROUP BY Suppliername, Status
HAVING CharList( 'A', 'B', 'C' )
       SUBMULTISET OF CAST( COLLECT( Item ) AS CharList )

<强> Results

| SUPPLIERNAME |   STATUS |
|--------------|----------|
|           S1 | Approved |

查询2

SELECT Suppliername, Status
FROM   table_name
WHERE  Item IN ( 'A', 'B', 'C' )
GROUP BY Suppliername, Status
HAVING COUNT( DISTINCT item ) = 3

<强> Results

| SUPPLIERNAME |   STATUS |
|--------------|----------|
|           S1 | Approved |

查询3

SELECT Suppliername, Status
FROM   table_name
WHERE  Item MEMBER OF CharList( 'A', 'B', 'C' )
GROUP BY Suppliername, Status
HAVING COUNT( DISTINCT item ) = CARDINALITY( CharList( 'A', 'B', 'C' ) )

<强> Results

| SUPPLIERNAME |   STATUS |
|--------------|----------|
|           S1 | Approved |

答案 1 :(得分:-1)

我就是这样做的:

WITH picklist(Item) AS
(
  VALUES ('A'),
         ('B'),
         ('C')
), grouping AS 
(
  SELECT T.Suppliername, T.Status, COUNT(*) AS C
  FROM TABLE T
  JOIN picklist ON T.Item = picklist.Item
  GROUP BY T.Suppliername, T.Status
)
SELECT Suppliername, Status
FROM grouping 
WHERE C = (SELECT COUNT(*) FROM picklist)

如果值在您的平台上不起作用,则可以用于SQL Server

 SELECT 'A' as Item
    UNION ALL
 SELECT 'B' as Item
    UNION ALL
 SELECT 'C' as Item

和For Oracle(根据MT0)

 SELECT 'A' as Item FROM DUAL
    UNION ALL
 SELECT 'B' as Item FROM DUAL
    UNION ALL
 SELECT 'C' as Item FROM DUAL