我有几列,我正在寻找一个SQL查询,它可以为我提供第4列和第5列的输出,当第一次看到值时,我的值为1,当它再次出现时,值将为0。
希望我的问题不是很复杂。
UniqueNameCount和UniqueDESCCount是我正在看的输出......
Inventory ID Name Description UniqueNameCount UniqueDESCCount
预期结果:
Inventory ID Name Description UniqueNameCount UniqueDESCCount
IN0001 Item 1 Desc 1 1 1
IN0002 Item 2 Desc 2 1 1
IN0003 Item 3 Desc 1 1 0
IN0004 Item 1 Desc 1 0 0
IN0005 Item 2 Desc 5 0 1
IN0006 Item 2 Desc 5 0 0
IN0007 Item 2 Desc 5 0 0
IN0008 Item 3 Desc 2 0 0
IN0009 Item 3 Desc 2 0 0
IN0010 Item 1 Desc 3 0 1
答案 0 :(得分:1)
使用相关的子查询来确定是否为较低的Inventory_ID查看了相同的名称或描述。
ON_COMMAND
可替换地:
select Inventory_ID, Name, Description,
case when exists (select 1 from tablename t2
where t2.Name = t1.name
and t2.Inventory_ID < t1.Inventory_ID) then 0
else 1
end as UniqueNameCount,
case when exists (select 1 from tablename t2
where t2.Description= t1.Description
and t2.Inventory_ID < t1.Inventory_ID) then 0
else 1
end as UniqueDESCCount
from tablename t1
答案 1 :(得分:1)
Oracle 11g R2架构设置:
CREATE TABLE table_name ( Inventory_ID, Name, Description ) AS
SELECT 'IN0001', 'Item 1', 'Desc 1' FROM DUAL
UNION ALL SELECT 'IN0002', 'Item 2', 'Desc 2' FROM DUAL
UNION ALL SELECT 'IN0003', 'Item 3', 'Desc 1' FROM DUAL
UNION ALL SELECT 'IN0004', 'Item 1', 'Desc 1' FROM DUAL
UNION ALL SELECT 'IN0005', 'Item 2', 'Desc 5' FROM DUAL
UNION ALL SELECT 'IN0006', 'Item 2', 'Desc 5' FROM DUAL
UNION ALL SELECT 'IN0007', 'Item 2', 'Desc 5' FROM DUAL
UNION ALL SELECT 'IN0008', 'Item 3', 'Desc 2' FROM DUAL
UNION ALL SELECT 'IN0009', 'Item 3', 'Desc 2' FROM DUAL
UNION ALL SELECT 'IN0010', 'Item 1', 'Desc 3' FROM DUAL;
查询1 :
SELECT Inventory_ID,
Name,
Description,
CASE
WHEN LAG( Name ) OVER ( PARTITION BY Name ORDER BY Inventory_ID ) IS NULL
THEN 1
ELSE 0
END AS UniqueNameCount,
CASE
WHEN LAG( Description ) OVER ( PARTITION BY Description ORDER BY Inventory_ID ) IS NULL
THEN 1
ELSE 0
END AS UniqueDESCCount
FROM table_name
ORDER BY Inventory_ID
<强> Results 强>:
| INVENTORY_ID | NAME | DESCRIPTION | UNIQUENAMECOUNT | UNIQUEDESCCOUNT |
|--------------|--------|-------------|-----------------|-----------------|
| IN0001 | Item 1 | Desc 1 | 1 | 1 |
| IN0002 | Item 2 | Desc 2 | 1 | 1 |
| IN0003 | Item 3 | Desc 1 | 1 | 0 |
| IN0004 | Item 1 | Desc 1 | 0 | 0 |
| IN0005 | Item 2 | Desc 5 | 0 | 1 |
| IN0006 | Item 2 | Desc 5 | 0 | 0 |
| IN0007 | Item 2 | Desc 5 | 0 | 0 |
| IN0008 | Item 3 | Desc 2 | 0 | 0 |
| IN0009 | Item 3 | Desc 2 | 0 | 0 |
| IN0010 | Item 1 | Desc 3 | 0 | 1 |