显示不同行中两列的重复值

时间:2013-01-16 06:33:42

标签: sql

我有一个表格,其中可以有两个特定值的报纸发布日期,仅在NewsPaperDate下插入一个列。所有剩余的值都会重复。现在我必须编写一个查询,其中两个NewsPaperDate值应该显示在两行,NewsPaperDate1和NewsPaperDate2下的单行中,其余值为enter image description here。任何人都可以帮助吗?数据库是Sql Server enter image description here 表结构是

3 个答案:

答案 0 :(得分:4)

您需要将表连接到自身。有不同的方法可以做到这一点,但根据你的截图,你可以做:

select 
    a.yonja_no, 
    a.newspaper_date as newspaperdate1, 
    b.newspaper_date as newspaperdate2
from newspapertable a, newspapertable b
where a.yonja_no = b.yonja_no
and a.newspapere_s > b.newspapere_s
;

(编辑:见评论)

答案 1 :(得分:2)

使用示例数据检查fiddle link查询执行情况

create table tab1(newspaperDate number,b number,c number);
INSERT INTO tab1 VALUES(1,2,3);
INSERT INTO tab1 VALUES(2,2,3);
INSERT INTO tab1 VALUES(3,3,4);


SELECT t1.newspaperDate AS date1,t2.newspaperDate AS date2 , t1.b AS b1,t1.c AS c1 FROM tab1   t1 , tab1   t2
WHERE t1.newspaperDate < t2.newspaperDate AND t1.b=t2.b ;

<强>输出

| DATE1 | DATE2 | B1 | C1 |
---------------------------
|     1 |     2 |  2 |  3 |

答案 2 :(得分:1)

  

将表连接到自身是查询的最佳方法。读   此

http://www.thunderstone.com/site/texisman/joining_a_table_to_itself.html