Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

sql - How to Select one Value for each row after Joining of 2 Tables

I have 2 tables, the first one has 10 distinct values:

First Table,

each GlobalPnID has many values on the second table, I want to join 2 tables and select one random value of PortionKey of the second table that match the condition and move to the next GlobalPnID

enter image description here

SELECT  TOP 10 gpnp.PortionKey, tt.GlobalPnID 
from #TempTable tt
LEFT JOIN [dbo].[GlobalPartNumberPortions] gpnp  ON gpnp.GlobalPnId = tt.GlobalPnID

-- tt is the  first table
-- gpnp is the second 
question from:https://stackoverflow.com/questions/65880709/how-to-select-one-value-for-each-row-after-joining-of-2-tables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
SELECT TT.GlobalPnID,X.PortionKey
FROM #TempTable AS TT
CROSS APPLY
 (
     SELECT TOP 1 R.PortionKey
       FROM [dbo].[GlobalPartNumberPortions] AS R
        WHERE R.GlobalPnId=TT.GlobalPnID
         ORDER BY R.PortionID
 )X

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...