找到丢失的记录

时间:2017-10-09 19:01:28

标签: sql oracle

三个表格按以下方式相互连接:
员工ID(ID,姓名)到员工ID(ID,Employee_id,Vendor_id,total_amount,date_paid) 按供应商ID的工资(ID,Employee_id,Vendor_id)到供应商(Id,名称) 每个员工ID至少有2个供应商 然而,所有员工都有一个供应商 - “ABC” 我需要一份供应商ABC没有付款的雇员名单 例如:

Employee Vendor Month Total_amount
123     ABC     Jan 150
123     DEF     Jan 200
456     ABC     Jan 150
456     XYZ     Jan 250
123     DEF     Feb 200
456     ABC     Feb 150
456     XYZ     Feb 250

我的结果应该是2月份的Employee_ID 123,因为那个月没有支付供应商ABC。

1 个答案:

答案 0 :(得分:0)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name ( Employee, Vendor, Month, Total_amount ) AS
SELECT 123, 'ABC', 'Jan', 150 FROM DUAL UNION ALL
SELECT 123, 'DEF', 'Jan', 200 FROM DUAL UNION ALL
SELECT 456, 'ABC', 'Jan', 150 FROM DUAL UNION ALL
SELECT 456, 'XYZ', 'Jan', 250 FROM DUAL UNION ALL
SELECT 123, 'DEF', 'Feb', 200 FROM DUAL UNION ALL
SELECT 456, 'ABC', 'Feb', 150 FROM DUAL UNION ALL
SELECT 456, 'XYZ', 'Feb', 250 FROM DUAL;

查询1

WITH EVA( Employee, Vendor, Total_Amount ) AS (
  SELECT DISTINCT
         Employee,
         Vendor,
         Total_Amount
  FROM   table_name
),
Months ( Month ) AS (
  SELECT DISTINCT MONTH FROM table_name
)
SELECT Employee, Vendor, Month, Total_Amount
FROM   EVA CROSS JOIN Months
MINUS
SELECT Employee, Vendor, Month, Total_Amount
FROM   table_name

<强> Results

| EMPLOYEE | VENDOR | MONTH | TOTAL_AMOUNT |
|----------|--------|-------|--------------|
|      123 |    ABC |   Feb |          150 |