oracle联接中具有内部联接的不同记录

时间:2013-05-01 09:24:28

标签: sql oracle inner-join

我使用以下查询返回记录列表:

Select DISTINCT A.Id Questionid,
  A.Created_Date Questiondate,
  Row_Number() Over ( Order By A.Created_Date Desc) Row_Id,
 B.Id Answerid,
 COUNT(*) OVER (partition by a.id) QCOUNT,
 B.Created_Date Answerdate
From Question_Table A
Inner Join Answers_Table B
ON A.Id      =  B.Question_Id
AND A.Is_Active = 1
AND A.Is_Delete = 0
And B.Is_Active = 1
And B.Is_Delete = 0 
And A.Category_Id = 1318221772

Answers_Table.question_id映射到question_table.id

因此,对于特定的问题id,answers_table上可以有多行。

现在显示的输出是:

QUESTIONID QUESTIONDATE ROW_ID ANSWERID QCOUNT ANSWERDATE

52776   08-DEC-12   1   31383   2   09-DEC-12
52776   08-DEC-12   2   31482   2   10-DEC-12
52719   07-DEC-12   3   31321   1   07-DEC-12

但我要求将输出显示为:

QUESTIONID QUESTIONDATE ROW_ID ANSWERID QCOUNT ANSWERDATE

52776   08-DEC-12   1   31383   2   09-DEC-12
52719   07-DEC-12   3   31321   1   07-DEC-12

如何在输出中显示唯一的questionid(如52776,52719)?

1 个答案:

答案 0 :(得分:0)

根据您的尝试,您可以使用Group By语句重写此内容。但是,如果您想保留现有查询,请尝试更改此行:

  Row_Number() Over (Order By A.Created_Date Desc) Row_Id,

到此:

  Row_Number() Over ( partition by a.id Order By B.Created_Date ASC) Row_Id,

然后让整个事情成为一个子查询,选择row_id = 1的位置。这应该只返回每个问题的一行,而且只是该问题的最早答案。

Select * From (
Select DISTINCT A.Id Questionid,
  A.Created_Date Questiondate,
  Row_Number() Over ( partition by a.id Order By B.Created_Date ASC) Row_Id,
 B.Id Answerid,
 COUNT(*) OVER (partition by a.id) QCOUNT,
 B.Created_Date Answerdate
From Question_Table A
Inner Join Answers_Table B
ON A.Id      =  B.Question_Id
AND A.Is_Active = 1
AND A.Is_Delete = 0
And B.Is_Active = 1
And B.Is_Delete = 0 
And A.Category_Id = 1318221772
) Where ROW_ID = 1