Get top 1 row value from third table while joining 3 tables mssql Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Top 2 rows per partition from an absolute value date differenceHelp with a complicated MySQL Query inserting data using select from 2 tablescount rows with same value and get column from other tableDistinct column in an inner join query sqlDISTINCT Query on an INNER JOINConcatenate multiple columns into one column (,) separatedHow can I properly merge the rows of several table with default values?MySQL: Grouping with conditionParallel updates on header and line item tables in SSISjoin two tables, include one row from the parent table for each primary key

calculator's angle answer for trig ratios that can work in more than 1 quadrant on the unit circle

Is the Mordenkainen's Sword spell underpowered?

Why did Bronn offer to be Tyrion Lannister's champion in trial by combat?

Did pre-Columbian Americans know the spherical shape of the Earth?

Can I cut the hair of a conjured korred with a blade made of precious material to harvest that material from the korred?

What did Turing mean when saying that "machines cannot give rise to surprises" is due to a fallacy?

How do Java 8 default methods hеlp with lambdas?

Flight departed from the gate 5 min before scheduled departure time. Refund options

Why does BitLocker not use RSA?

Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?

An isoperimetric-type inequality inside a cube

Should man-made satellites feature an intelligent inverted "cow catcher"?

Combining list in a Cartesian product format with addition operation?

Getting representations of the Lie group out of representations of its Lie algebra

Why not use the yoke to control yaw, as well as pitch and roll?

Can two people see the same photon?

Why are current probes so expensive?

How to name indistinguishable henchmen in a screenplay?

How does TikZ render an arc?

Where did Ptolemy compare the Earth to the distance of fixed stars?

Improvising over quartal voicings

.bashrc alias for a command with fixed second parameter

Why can't fire hurt Daenerys but it did to Jon Snow in season 1?

3D Masyu - A Die



Get top 1 row value from third table while joining 3 tables mssql



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Top 2 rows per partition from an absolute value date differenceHelp with a complicated MySQL Query inserting data using select from 2 tablescount rows with same value and get column from other tableDistinct column in an inner join query sqlDISTINCT Query on an INNER JOINConcatenate multiple columns into one column (,) separatedHow can I properly merge the rows of several table with default values?MySQL: Grouping with conditionParallel updates on header and line item tables in SSISjoin two tables, include one row from the parent table for each primary key



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















I am new to mssql .here I need to get some data using joins between three tables .



Header join Lines join Images --> Result



Header Table :



enter image description here



Line Table :



enter image description here



For each header record we can have multiple line items .



Images Table :



enter image description here



Each Image will have unique Image or multiple images .Need to get 1 image url from the list of items for the header record.



Result Set :



enter image description here



Query :



SELECT HT.O_ID,
HT.Type,
HT.Total,
IM.Image

FROM HEADER_TABLE HT

JOIN LINE_ITEM_TABLE LIT
ON LIT.O_ID = HT.O_ID

JOIN IMAGE_TABLE IT
ON IT.IMAGE = LIT.ITEM_ID

WHERE IT.SECTION = 'Retail'


This query returns multiple rows .But I need one unique row for each Header record.



Can anyone help me to fix .










share|improve this question

















  • 4





    Hi and welcome to DBA.SE! The table create + insert statements could be useful to get an answer faster. (Testing purposes)

    – Randi Vertongen
    Mar 19 at 13:32











  • I need one unique row for each Header record. If so you MUST to build a criteria which will say what record from all record pack with the same header must be returned.

    – Akina
    Mar 19 at 13:32












  • Can you check and possibly update a couple of things in your question? Your SQL statement as currently written should return no rows; the second join needs to say on IT.ITEM_ID = LIT.ITEM_ID. Also, the sample data that you've included doesn't show any duplicates on the ITEM_ID field, so it doesn't look like the query (with the corrected join) would have any duplicates either. Are there actually multiple rows per Item ID in that table?

    – Hellion
    Mar 19 at 17:34

















3















I am new to mssql .here I need to get some data using joins between three tables .



Header join Lines join Images --> Result



Header Table :



enter image description here



Line Table :



enter image description here



For each header record we can have multiple line items .



Images Table :



enter image description here



Each Image will have unique Image or multiple images .Need to get 1 image url from the list of items for the header record.



Result Set :



enter image description here



Query :



SELECT HT.O_ID,
HT.Type,
HT.Total,
IM.Image

FROM HEADER_TABLE HT

JOIN LINE_ITEM_TABLE LIT
ON LIT.O_ID = HT.O_ID

JOIN IMAGE_TABLE IT
ON IT.IMAGE = LIT.ITEM_ID

WHERE IT.SECTION = 'Retail'


This query returns multiple rows .But I need one unique row for each Header record.



Can anyone help me to fix .










share|improve this question

















  • 4





    Hi and welcome to DBA.SE! The table create + insert statements could be useful to get an answer faster. (Testing purposes)

    – Randi Vertongen
    Mar 19 at 13:32











  • I need one unique row for each Header record. If so you MUST to build a criteria which will say what record from all record pack with the same header must be returned.

    – Akina
    Mar 19 at 13:32












  • Can you check and possibly update a couple of things in your question? Your SQL statement as currently written should return no rows; the second join needs to say on IT.ITEM_ID = LIT.ITEM_ID. Also, the sample data that you've included doesn't show any duplicates on the ITEM_ID field, so it doesn't look like the query (with the corrected join) would have any duplicates either. Are there actually multiple rows per Item ID in that table?

    – Hellion
    Mar 19 at 17:34













3












3








3








I am new to mssql .here I need to get some data using joins between three tables .



Header join Lines join Images --> Result



Header Table :



enter image description here



Line Table :



enter image description here



For each header record we can have multiple line items .



Images Table :



enter image description here



Each Image will have unique Image or multiple images .Need to get 1 image url from the list of items for the header record.



Result Set :



enter image description here



Query :



SELECT HT.O_ID,
HT.Type,
HT.Total,
IM.Image

FROM HEADER_TABLE HT

JOIN LINE_ITEM_TABLE LIT
ON LIT.O_ID = HT.O_ID

JOIN IMAGE_TABLE IT
ON IT.IMAGE = LIT.ITEM_ID

WHERE IT.SECTION = 'Retail'


This query returns multiple rows .But I need one unique row for each Header record.



Can anyone help me to fix .










share|improve this question














I am new to mssql .here I need to get some data using joins between three tables .



Header join Lines join Images --> Result



Header Table :



enter image description here



Line Table :



enter image description here



For each header record we can have multiple line items .



Images Table :



enter image description here



Each Image will have unique Image or multiple images .Need to get 1 image url from the list of items for the header record.



Result Set :



enter image description here



Query :



SELECT HT.O_ID,
HT.Type,
HT.Total,
IM.Image

FROM HEADER_TABLE HT

JOIN LINE_ITEM_TABLE LIT
ON LIT.O_ID = HT.O_ID

JOIN IMAGE_TABLE IT
ON IT.IMAGE = LIT.ITEM_ID

WHERE IT.SECTION = 'Retail'


This query returns multiple rows .But I need one unique row for each Header record.



Can anyone help me to fix .







sql-server sql-server-2012 join stored-procedures






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 19 at 13:28









ZhuZhu

1161




1161







  • 4





    Hi and welcome to DBA.SE! The table create + insert statements could be useful to get an answer faster. (Testing purposes)

    – Randi Vertongen
    Mar 19 at 13:32











  • I need one unique row for each Header record. If so you MUST to build a criteria which will say what record from all record pack with the same header must be returned.

    – Akina
    Mar 19 at 13:32












  • Can you check and possibly update a couple of things in your question? Your SQL statement as currently written should return no rows; the second join needs to say on IT.ITEM_ID = LIT.ITEM_ID. Also, the sample data that you've included doesn't show any duplicates on the ITEM_ID field, so it doesn't look like the query (with the corrected join) would have any duplicates either. Are there actually multiple rows per Item ID in that table?

    – Hellion
    Mar 19 at 17:34












  • 4





    Hi and welcome to DBA.SE! The table create + insert statements could be useful to get an answer faster. (Testing purposes)

    – Randi Vertongen
    Mar 19 at 13:32











  • I need one unique row for each Header record. If so you MUST to build a criteria which will say what record from all record pack with the same header must be returned.

    – Akina
    Mar 19 at 13:32












  • Can you check and possibly update a couple of things in your question? Your SQL statement as currently written should return no rows; the second join needs to say on IT.ITEM_ID = LIT.ITEM_ID. Also, the sample data that you've included doesn't show any duplicates on the ITEM_ID field, so it doesn't look like the query (with the corrected join) would have any duplicates either. Are there actually multiple rows per Item ID in that table?

    – Hellion
    Mar 19 at 17:34







4




4





Hi and welcome to DBA.SE! The table create + insert statements could be useful to get an answer faster. (Testing purposes)

– Randi Vertongen
Mar 19 at 13:32





Hi and welcome to DBA.SE! The table create + insert statements could be useful to get an answer faster. (Testing purposes)

– Randi Vertongen
Mar 19 at 13:32













I need one unique row for each Header record. If so you MUST to build a criteria which will say what record from all record pack with the same header must be returned.

– Akina
Mar 19 at 13:32






I need one unique row for each Header record. If so you MUST to build a criteria which will say what record from all record pack with the same header must be returned.

– Akina
Mar 19 at 13:32














Can you check and possibly update a couple of things in your question? Your SQL statement as currently written should return no rows; the second join needs to say on IT.ITEM_ID = LIT.ITEM_ID. Also, the sample data that you've included doesn't show any duplicates on the ITEM_ID field, so it doesn't look like the query (with the corrected join) would have any duplicates either. Are there actually multiple rows per Item ID in that table?

– Hellion
Mar 19 at 17:34





Can you check and possibly update a couple of things in your question? Your SQL statement as currently written should return no rows; the second join needs to say on IT.ITEM_ID = LIT.ITEM_ID. Also, the sample data that you've included doesn't show any duplicates on the ITEM_ID field, so it doesn't look like the query (with the corrected join) would have any duplicates either. Are there actually multiple rows per Item ID in that table?

– Hellion
Mar 19 at 17:34










2 Answers
2






active

oldest

votes


















5














You can use CROSS APPLY to SELECT just the TOP 1 image from each particular header. APPLY is similar to a function you can create "on the go" that links columns or expressions from outside to it's filters or joins.



SELECT
-- Header columns:
HT.O_ID,
HT.Type,
HT.Total,

-- Columns from the CROSS APPLY result
I.Image
FROM
HEADER_TABLE HT
CROSS APPLY (
SELECT TOP 1 -- Just retrieve 1 row (for each HT row)
IT.IMAGE
FROM
LINE_ITEM_TABLE LIT
INNER JOIN IMAGE_TABLE IT ON IT.ITEM_ID = LIT.ITEM_ID
WHERE
LIT.O_ID = HT.O_ID AND -- Link the outmost header "HT" record to it's lines "LIT"
IT.SECTION = 'Retail') AS I


You can add an ORDER BY inside the CROSS APPLY to determine which image will get selected. You can also change the CROSS APPLY to OUTER APPLY if you want header rows to display even when there is no matching record coming from the APPLY operator (the IMAGE column will be NULL).






share|improve this answer






























    3















    But I need one unique row for each Header record.




    To me it is unclear if you mean one unique record per HT.O_ID or no duplicate records regarding all the four columns returned.



    If it is the latter, add the DISTINCT keyword to your query (and add the schema names).



     SELECT DISTINCT HT.O_ID,
    HT.Type,
    HT.Total,
    IT.Image

    FROM dbo.HEADER_TABLE HT
    JOIN dbo.LINE_ITEM_TABLE LIT
    ON LIT.O_ID = HT.O_ID
    JOIN dbo.IMAGE_TABLE IT
    ON IT.Item_ID = LIT.ITEM_ID
    WHERE IT.SECTION = 'Retail';


    Result



    O_ID Type Total Image
    1001 Online $10 URL


    If that does not solve it



    Then you would have to group by the values in the Header_Table And decide which Image you need to keep,do concatenation on it, ....



    SELECT HT.O_ID,
    HT.Type,
    HT.Total,
    MAX(IT.Image) as MaxURL

    FROM dbo.HEADER_TABLE HT
    JOIN dbo.LINE_ITEM_TABLE LIT
    ON LIT.O_ID = HT.O_ID
    JOIN dbo.IMAGE_TABLE IT
    ON IT.Item_ID = LIT.ITEM_ID
    WHERE IT.SECTION = 'Retail'
    GROUP BY HT.O_ID,HT.Type,HT.Total;



    Test data



    CREATE TABLE dbo.HEADER_TABLE(O_ID int,Type varchar(100),Total varchar(10))
    INSERT INTO dbo.HEADER_TABLE(O_ID,Type,Total)
    VALUES (1001,'Online','$10');

    CREATE TABLE dbo.LINE_ITEM_TABLE(ID int,O_ID int,Item_ID varchar(4),Line_Total varchar(10));
    INSERT INTO dbo.LINE_ITEM_TABLE(ID,O_ID,Item_ID,Line_Total)
    VALUES (1,1001,'P001','$2'),
    (2,1001,'P002','$2'),
    (3,1001,'P003','$2'),
    (4,1001,'P004','$2'),
    (5,1001,'P005','$2');


    CREATE TABLE dbo.IMAGE_TABLE(Item_ID varchar(10),Image varchar(100),Section varchar(10))
    INSERT INTO dbo.IMAGE_TABLE
    VALUES ('P001','URL','Retail'),
    ('P002','URL','Retail'),
    ('P003','URL','Stock'),
    ('P004','URL','Retail'),
    ('P005','URL','Retail');





    share|improve this answer

























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "182"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f232523%2fget-top-1-row-value-from-third-table-while-joining-3-tables-mssql%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      5














      You can use CROSS APPLY to SELECT just the TOP 1 image from each particular header. APPLY is similar to a function you can create "on the go" that links columns or expressions from outside to it's filters or joins.



      SELECT
      -- Header columns:
      HT.O_ID,
      HT.Type,
      HT.Total,

      -- Columns from the CROSS APPLY result
      I.Image
      FROM
      HEADER_TABLE HT
      CROSS APPLY (
      SELECT TOP 1 -- Just retrieve 1 row (for each HT row)
      IT.IMAGE
      FROM
      LINE_ITEM_TABLE LIT
      INNER JOIN IMAGE_TABLE IT ON IT.ITEM_ID = LIT.ITEM_ID
      WHERE
      LIT.O_ID = HT.O_ID AND -- Link the outmost header "HT" record to it's lines "LIT"
      IT.SECTION = 'Retail') AS I


      You can add an ORDER BY inside the CROSS APPLY to determine which image will get selected. You can also change the CROSS APPLY to OUTER APPLY if you want header rows to display even when there is no matching record coming from the APPLY operator (the IMAGE column will be NULL).






      share|improve this answer



























        5














        You can use CROSS APPLY to SELECT just the TOP 1 image from each particular header. APPLY is similar to a function you can create "on the go" that links columns or expressions from outside to it's filters or joins.



        SELECT
        -- Header columns:
        HT.O_ID,
        HT.Type,
        HT.Total,

        -- Columns from the CROSS APPLY result
        I.Image
        FROM
        HEADER_TABLE HT
        CROSS APPLY (
        SELECT TOP 1 -- Just retrieve 1 row (for each HT row)
        IT.IMAGE
        FROM
        LINE_ITEM_TABLE LIT
        INNER JOIN IMAGE_TABLE IT ON IT.ITEM_ID = LIT.ITEM_ID
        WHERE
        LIT.O_ID = HT.O_ID AND -- Link the outmost header "HT" record to it's lines "LIT"
        IT.SECTION = 'Retail') AS I


        You can add an ORDER BY inside the CROSS APPLY to determine which image will get selected. You can also change the CROSS APPLY to OUTER APPLY if you want header rows to display even when there is no matching record coming from the APPLY operator (the IMAGE column will be NULL).






        share|improve this answer

























          5












          5








          5







          You can use CROSS APPLY to SELECT just the TOP 1 image from each particular header. APPLY is similar to a function you can create "on the go" that links columns or expressions from outside to it's filters or joins.



          SELECT
          -- Header columns:
          HT.O_ID,
          HT.Type,
          HT.Total,

          -- Columns from the CROSS APPLY result
          I.Image
          FROM
          HEADER_TABLE HT
          CROSS APPLY (
          SELECT TOP 1 -- Just retrieve 1 row (for each HT row)
          IT.IMAGE
          FROM
          LINE_ITEM_TABLE LIT
          INNER JOIN IMAGE_TABLE IT ON IT.ITEM_ID = LIT.ITEM_ID
          WHERE
          LIT.O_ID = HT.O_ID AND -- Link the outmost header "HT" record to it's lines "LIT"
          IT.SECTION = 'Retail') AS I


          You can add an ORDER BY inside the CROSS APPLY to determine which image will get selected. You can also change the CROSS APPLY to OUTER APPLY if you want header rows to display even when there is no matching record coming from the APPLY operator (the IMAGE column will be NULL).






          share|improve this answer













          You can use CROSS APPLY to SELECT just the TOP 1 image from each particular header. APPLY is similar to a function you can create "on the go" that links columns or expressions from outside to it's filters or joins.



          SELECT
          -- Header columns:
          HT.O_ID,
          HT.Type,
          HT.Total,

          -- Columns from the CROSS APPLY result
          I.Image
          FROM
          HEADER_TABLE HT
          CROSS APPLY (
          SELECT TOP 1 -- Just retrieve 1 row (for each HT row)
          IT.IMAGE
          FROM
          LINE_ITEM_TABLE LIT
          INNER JOIN IMAGE_TABLE IT ON IT.ITEM_ID = LIT.ITEM_ID
          WHERE
          LIT.O_ID = HT.O_ID AND -- Link the outmost header "HT" record to it's lines "LIT"
          IT.SECTION = 'Retail') AS I


          You can add an ORDER BY inside the CROSS APPLY to determine which image will get selected. You can also change the CROSS APPLY to OUTER APPLY if you want header rows to display even when there is no matching record coming from the APPLY operator (the IMAGE column will be NULL).







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 19 at 13:47









          EzLoEzLo

          2,9231621




          2,9231621























              3















              But I need one unique row for each Header record.




              To me it is unclear if you mean one unique record per HT.O_ID or no duplicate records regarding all the four columns returned.



              If it is the latter, add the DISTINCT keyword to your query (and add the schema names).



               SELECT DISTINCT HT.O_ID,
              HT.Type,
              HT.Total,
              IT.Image

              FROM dbo.HEADER_TABLE HT
              JOIN dbo.LINE_ITEM_TABLE LIT
              ON LIT.O_ID = HT.O_ID
              JOIN dbo.IMAGE_TABLE IT
              ON IT.Item_ID = LIT.ITEM_ID
              WHERE IT.SECTION = 'Retail';


              Result



              O_ID Type Total Image
              1001 Online $10 URL


              If that does not solve it



              Then you would have to group by the values in the Header_Table And decide which Image you need to keep,do concatenation on it, ....



              SELECT HT.O_ID,
              HT.Type,
              HT.Total,
              MAX(IT.Image) as MaxURL

              FROM dbo.HEADER_TABLE HT
              JOIN dbo.LINE_ITEM_TABLE LIT
              ON LIT.O_ID = HT.O_ID
              JOIN dbo.IMAGE_TABLE IT
              ON IT.Item_ID = LIT.ITEM_ID
              WHERE IT.SECTION = 'Retail'
              GROUP BY HT.O_ID,HT.Type,HT.Total;



              Test data



              CREATE TABLE dbo.HEADER_TABLE(O_ID int,Type varchar(100),Total varchar(10))
              INSERT INTO dbo.HEADER_TABLE(O_ID,Type,Total)
              VALUES (1001,'Online','$10');

              CREATE TABLE dbo.LINE_ITEM_TABLE(ID int,O_ID int,Item_ID varchar(4),Line_Total varchar(10));
              INSERT INTO dbo.LINE_ITEM_TABLE(ID,O_ID,Item_ID,Line_Total)
              VALUES (1,1001,'P001','$2'),
              (2,1001,'P002','$2'),
              (3,1001,'P003','$2'),
              (4,1001,'P004','$2'),
              (5,1001,'P005','$2');


              CREATE TABLE dbo.IMAGE_TABLE(Item_ID varchar(10),Image varchar(100),Section varchar(10))
              INSERT INTO dbo.IMAGE_TABLE
              VALUES ('P001','URL','Retail'),
              ('P002','URL','Retail'),
              ('P003','URL','Stock'),
              ('P004','URL','Retail'),
              ('P005','URL','Retail');





              share|improve this answer





























                3















                But I need one unique row for each Header record.




                To me it is unclear if you mean one unique record per HT.O_ID or no duplicate records regarding all the four columns returned.



                If it is the latter, add the DISTINCT keyword to your query (and add the schema names).



                 SELECT DISTINCT HT.O_ID,
                HT.Type,
                HT.Total,
                IT.Image

                FROM dbo.HEADER_TABLE HT
                JOIN dbo.LINE_ITEM_TABLE LIT
                ON LIT.O_ID = HT.O_ID
                JOIN dbo.IMAGE_TABLE IT
                ON IT.Item_ID = LIT.ITEM_ID
                WHERE IT.SECTION = 'Retail';


                Result



                O_ID Type Total Image
                1001 Online $10 URL


                If that does not solve it



                Then you would have to group by the values in the Header_Table And decide which Image you need to keep,do concatenation on it, ....



                SELECT HT.O_ID,
                HT.Type,
                HT.Total,
                MAX(IT.Image) as MaxURL

                FROM dbo.HEADER_TABLE HT
                JOIN dbo.LINE_ITEM_TABLE LIT
                ON LIT.O_ID = HT.O_ID
                JOIN dbo.IMAGE_TABLE IT
                ON IT.Item_ID = LIT.ITEM_ID
                WHERE IT.SECTION = 'Retail'
                GROUP BY HT.O_ID,HT.Type,HT.Total;



                Test data



                CREATE TABLE dbo.HEADER_TABLE(O_ID int,Type varchar(100),Total varchar(10))
                INSERT INTO dbo.HEADER_TABLE(O_ID,Type,Total)
                VALUES (1001,'Online','$10');

                CREATE TABLE dbo.LINE_ITEM_TABLE(ID int,O_ID int,Item_ID varchar(4),Line_Total varchar(10));
                INSERT INTO dbo.LINE_ITEM_TABLE(ID,O_ID,Item_ID,Line_Total)
                VALUES (1,1001,'P001','$2'),
                (2,1001,'P002','$2'),
                (3,1001,'P003','$2'),
                (4,1001,'P004','$2'),
                (5,1001,'P005','$2');


                CREATE TABLE dbo.IMAGE_TABLE(Item_ID varchar(10),Image varchar(100),Section varchar(10))
                INSERT INTO dbo.IMAGE_TABLE
                VALUES ('P001','URL','Retail'),
                ('P002','URL','Retail'),
                ('P003','URL','Stock'),
                ('P004','URL','Retail'),
                ('P005','URL','Retail');





                share|improve this answer



























                  3












                  3








                  3








                  But I need one unique row for each Header record.




                  To me it is unclear if you mean one unique record per HT.O_ID or no duplicate records regarding all the four columns returned.



                  If it is the latter, add the DISTINCT keyword to your query (and add the schema names).



                   SELECT DISTINCT HT.O_ID,
                  HT.Type,
                  HT.Total,
                  IT.Image

                  FROM dbo.HEADER_TABLE HT
                  JOIN dbo.LINE_ITEM_TABLE LIT
                  ON LIT.O_ID = HT.O_ID
                  JOIN dbo.IMAGE_TABLE IT
                  ON IT.Item_ID = LIT.ITEM_ID
                  WHERE IT.SECTION = 'Retail';


                  Result



                  O_ID Type Total Image
                  1001 Online $10 URL


                  If that does not solve it



                  Then you would have to group by the values in the Header_Table And decide which Image you need to keep,do concatenation on it, ....



                  SELECT HT.O_ID,
                  HT.Type,
                  HT.Total,
                  MAX(IT.Image) as MaxURL

                  FROM dbo.HEADER_TABLE HT
                  JOIN dbo.LINE_ITEM_TABLE LIT
                  ON LIT.O_ID = HT.O_ID
                  JOIN dbo.IMAGE_TABLE IT
                  ON IT.Item_ID = LIT.ITEM_ID
                  WHERE IT.SECTION = 'Retail'
                  GROUP BY HT.O_ID,HT.Type,HT.Total;



                  Test data



                  CREATE TABLE dbo.HEADER_TABLE(O_ID int,Type varchar(100),Total varchar(10))
                  INSERT INTO dbo.HEADER_TABLE(O_ID,Type,Total)
                  VALUES (1001,'Online','$10');

                  CREATE TABLE dbo.LINE_ITEM_TABLE(ID int,O_ID int,Item_ID varchar(4),Line_Total varchar(10));
                  INSERT INTO dbo.LINE_ITEM_TABLE(ID,O_ID,Item_ID,Line_Total)
                  VALUES (1,1001,'P001','$2'),
                  (2,1001,'P002','$2'),
                  (3,1001,'P003','$2'),
                  (4,1001,'P004','$2'),
                  (5,1001,'P005','$2');


                  CREATE TABLE dbo.IMAGE_TABLE(Item_ID varchar(10),Image varchar(100),Section varchar(10))
                  INSERT INTO dbo.IMAGE_TABLE
                  VALUES ('P001','URL','Retail'),
                  ('P002','URL','Retail'),
                  ('P003','URL','Stock'),
                  ('P004','URL','Retail'),
                  ('P005','URL','Retail');





                  share|improve this answer
















                  But I need one unique row for each Header record.




                  To me it is unclear if you mean one unique record per HT.O_ID or no duplicate records regarding all the four columns returned.



                  If it is the latter, add the DISTINCT keyword to your query (and add the schema names).



                   SELECT DISTINCT HT.O_ID,
                  HT.Type,
                  HT.Total,
                  IT.Image

                  FROM dbo.HEADER_TABLE HT
                  JOIN dbo.LINE_ITEM_TABLE LIT
                  ON LIT.O_ID = HT.O_ID
                  JOIN dbo.IMAGE_TABLE IT
                  ON IT.Item_ID = LIT.ITEM_ID
                  WHERE IT.SECTION = 'Retail';


                  Result



                  O_ID Type Total Image
                  1001 Online $10 URL


                  If that does not solve it



                  Then you would have to group by the values in the Header_Table And decide which Image you need to keep,do concatenation on it, ....



                  SELECT HT.O_ID,
                  HT.Type,
                  HT.Total,
                  MAX(IT.Image) as MaxURL

                  FROM dbo.HEADER_TABLE HT
                  JOIN dbo.LINE_ITEM_TABLE LIT
                  ON LIT.O_ID = HT.O_ID
                  JOIN dbo.IMAGE_TABLE IT
                  ON IT.Item_ID = LIT.ITEM_ID
                  WHERE IT.SECTION = 'Retail'
                  GROUP BY HT.O_ID,HT.Type,HT.Total;



                  Test data



                  CREATE TABLE dbo.HEADER_TABLE(O_ID int,Type varchar(100),Total varchar(10))
                  INSERT INTO dbo.HEADER_TABLE(O_ID,Type,Total)
                  VALUES (1001,'Online','$10');

                  CREATE TABLE dbo.LINE_ITEM_TABLE(ID int,O_ID int,Item_ID varchar(4),Line_Total varchar(10));
                  INSERT INTO dbo.LINE_ITEM_TABLE(ID,O_ID,Item_ID,Line_Total)
                  VALUES (1,1001,'P001','$2'),
                  (2,1001,'P002','$2'),
                  (3,1001,'P003','$2'),
                  (4,1001,'P004','$2'),
                  (5,1001,'P005','$2');


                  CREATE TABLE dbo.IMAGE_TABLE(Item_ID varchar(10),Image varchar(100),Section varchar(10))
                  INSERT INTO dbo.IMAGE_TABLE
                  VALUES ('P001','URL','Retail'),
                  ('P002','URL','Retail'),
                  ('P003','URL','Stock'),
                  ('P004','URL','Retail'),
                  ('P005','URL','Retail');






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 19 at 13:47

























                  answered Mar 19 at 13:40









                  Randi VertongenRandi Vertongen

                  5,0711924




                  5,0711924



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Database Administrators Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f232523%2fget-top-1-row-value-from-third-table-while-joining-3-tables-mssql%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Identifying “long and narrow” polygons in with PostGISlength and width of polygonWhy postgis st_overlaps reports Qgis' “avoid intersections” generated polygon as overlapping with others?Adjusting polygons to boundary and filling holesDrawing polygons with fixed area?How to remove spikes in Polygons with PostGISDeleting sliver polygons after difference operation in QGIS?Snapping boundaries in PostGISSplit polygon into parts adding attributes based on underlying polygon in QGISSplitting overlap between polygons and assign to nearest polygon using PostGIS?Expanding polygons and clipping at midpoint?Removing Intersection of Buffers in Same Layers

                      Masuk log Menu navigasi

                      อาณาจักร (ชีววิทยา) ดูเพิ่ม อ้างอิง รายการเลือกการนำทาง10.1086/39456810.5962/bhl.title.447410.1126/science.163.3863.150576276010.1007/BF01796092408502"Phylogenetic structure of the prokaryotic domain: the primary kingdoms"10.1073/pnas.74.11.5088432104270744"Towards a natural system of organisms: proposal for the domains Archaea, Bacteria, and Eucarya"1990PNAS...87.4576W10.1073/pnas.87.12.4576541592112744PubMedJump the queueexpand by handPubMedJump the queueexpand by handPubMedJump the queueexpand by hand"A revised six-kingdom system of life"10.1111/j.1469-185X.1998.tb00030.x9809012"Only six kingdoms of life"10.1098/rspb.2004.2705169172415306349"Kingdoms Protozoa and Chromista and the eozoan root of the eukaryotic tree"10.1098/rsbl.2009.0948288006020031978เพิ่มข้อมูล