通过某些列查找重复值,而在其他列中查找不同

时间:2018-01-29 12:32:50

标签: sql oracle

我有这些表

article  type    date

apple    fruit   20180120
apple    fruit   20180119
banana   fruit   20180120
banana   fruit   20180120

我怎么能得到:

apple fruit 20180120
apple fruit 20180119

我正在尝试查找具有文章和类型等于和日期不同的寄存器。 谢谢,抱歉我的英文!

2 个答案:

答案 0 :(得分:0)

为此,您可以按照您的密钥(文章,类型)对记录进行分组。 仅当只有一条记录(HAVING条件)时才将组包含到输出中

select article, type, min(date) as date
from your_table
group by article, type
having count(*) = 1

第二次尝试:

select article, type, date
from your_table
group by article, type, date
having count(*) = 1

答案 1 :(得分:0)

使用COUNT( DISTINCT .. ) OVER ( PARTITION BY .. )分析函数计算每个分区中非重复(即DISTINCT)行的数量:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE your_table ( article, type, "date" ) AS
SELECT 'apple',  'fruit', DATE '2018-01-20' FROM DUAL UNION ALL
SELECT 'apple',  'fruit', DATE '2018-01-19' FROM DUAL UNION ALL
SELECT 'banana', 'fruit', DATE '2018-01-20' FROM DUAL UNION ALL
SELECT 'banana', 'fruit', DATE '2018-01-20' FROM DUAL

查询1

SELECT article,
       type,
       "date"
FROM   (
  SELECT t.*,
         COUNT( DISTINCT "date" ) OVER ( PARTITION BY article, type ) AS ct
  FROM   your_table t
)
WHERE  ct > 1

<强> Results

| ARTICLE |  TYPE |                 date |
|---------|-------|----------------------|
|   apple | fruit | 2018-01-19T00:00:00Z |
|   apple | fruit | 2018-01-20T00:00:00Z |