使用连接将两个不同表的两列相乘时重复行

时间:2018-06-04 08:14:24

标签: sql sql-server join

我有以下表格

  1. Question_Segment_Master
  2. Question_Set_Details
  3. 当我加入这两个表时,我得到重复的行.. 请查看小提琴,我发布了这两个模式及其数据..

    http://sqlfiddle.com/#!18/4c84f/10

    这是我期望的OP

    enter image description here

2 个答案:

答案 0 :(得分:1)

您需要获取每个细分的问题标记。此外,您应该使用branch_id,test_id,subject_code_id以及segment_id来加入。

使用JOIN然后选择不同的值

SELECT DISTINCT qsm.segment_id, segment_name, segment_description
  , must_attend_question AS tot_attented_question, total_question AS tot_questions
  , (qsd.question_marks * must_attend_question) AS tot_marks
  , '' AS marks_obtain
FROM dbo.Question_Segment_Master AS qsm
INNER JOIN dbo.Question_Set_Details AS qsd
ON (qsd.branch_id = qsm.branch_id AND qsd.test_id = qsm.test_id
AND qsd.segment_id = qsm.segment_id AND qsd.subject_code_id = qsm.subject_code_id)
WHERE qsm.subject_code_id = 1 and qsm.test_id = 1 and qsm.branch_id = 15;

Demo

答案 1 :(得分:1)

您错过了join子句中的segment_id

SELECT DISTINCT
        qsm.segment_id,
        qsm.segment_name,
        qsm.segment_description,
        qsm.must_attend_question tot_attented_question,
        qsm.total_question tot_questions,
        (qsd.question_marks * must_attend_question) tot_marks,
        '' AS marks_obtain
FROM dbo.question_segment_master qsm 
INNER JOIN dbo.question_set_details qsd on
                                        qsd.test_id = qsm.test_id
                                        and qsd.segment_id = qsm.segment_id
WHERE qsm.test_id=1
      AND qsm.branch_id = 15 
      AND qsm.subject_code_id =1 AND qsd.question_set_id = 1