如何从3行中获得一行,其中所有列都具有相同的ID,但其他数据不相同

时间:2019-11-01 10:00:03

标签: mysql database oracle

SELECT
    isbn13,
    MAX(TITLE) as TIT,
    MAX(PUBLISHER) as PUB,
   MAX(PUBLICATION_DATE)as P_DATE,
   MAX(PUBLICATION_COUNTRY_LOCATION) as P_C_LOC,
   MAX(BISAC_CODES) as B_CODES,
   MAX(BIC_SUBJECT_CODE)as B_S_CODES,
   MAX(FLEXFIELD2) as B_style,
   MAX(FLEXFIELD3) as lam_type,
   MAX(FLEXFIELD5) as color_text,
   MAX(FLEXFIELD6) as cover_color,
   MAX(FLEXFIELD7) as paper_type,
   MAX(FLEXFIELD8) as GSM,
   MAX(FLEXFIELD9) as casing,
   MAX(FLEXFIELD10) as spine,
   MAX(FLEXFIELD10) as thickness,
   MAX(FLEXFIELD12) as height,
   MAX(FLEXFIELD13) as width,
   MAX(PAGE_COUNT) as P_count
FROM
    (select isbn13,TITLE,PUBLISHER,PUBLICATION_DATE,PUBLICATION_COUNTRY_LOCATION,BISAC_CODES,BIC_SUBJECT_CODE,
    FLEXFIELD2,FLEXFIELD3,FLEXFIELD5,FLEXFIELD6,FLEXFIELD7,FLEXFIELD8,FLEXFIELD9,FLEXFIELD10,FLEXFIELD12,FLEXFIELD13,PAGE_COUNT,
     ROWNUM as rn from(select * from catalog_master ORDER BY cat_id ASC)
    union
    select isbn13,TITLE,PUBLISHER,PUBLICATION_DATE,PUBLICATION_COUNTRY_LOCATION,BISAC_CODES,BIC_SUBJECT_CODE,
    FLEXFIELD2,FLEXFIELD3,FLEXFIELD5,FLEXFIELD6,FLEXFIELD7,FLEXFIELD8,FLEXFIELD9,FLEXFIELD10,FLEXFIELD12,FLEXFIELD13,PAGE_COUNT,
    rownum as rn from (select * from sec_catalog_master ORDER BY cat_id ASC)
    )
where rn>0 and rn<=100
GROUP BY isbn13
ORDER BY isbn13 ASC

我在数据库中有一个表,该表的ID是唯一的,但在源端,该ID是重复的。与该重复ID有关的可用数据不相同。所以我想从那些重复的ID中获得一行。

我试图在SQL中使用MAX和MIN函数,但这会给我不好的数据。

我希望得到与运行查询时类似的结果。我想要从所有重复项中排一行的数据。

1 个答案:

答案 0 :(得分:0)

您可以使用解析row_number()函数来执行此操作,例如:

select id,
       col2,
       col3,
       ...
       orderby_col
from   (select yt.id,
               yt.col2,
               yt.col3, 
               ...
               yt.orderby_col
               row_number() over (partition by yt.id order by yt.orderby_col) rn
        from   your_table)
where  rn = 1;

这是通过使用partition by子句中的列(可以是多列)将数据分组为一组,然后按照{中的列所指定的顺序,向它们应用行号来进行的。 {1}}子句。

在为每组ID加上标签后,就可以从每个组中选择第一行。