使用内部联接返回每个id一行

时间:2014-05-10 07:08:24

标签: sql select join sql-server-2008-r2 distinct

在SQL Server数据库中,我有两个表,一个是另一个的父表。子表与父项具有多对一关系。我需要为每个父级返回一条记录,其中包含最相应的子表记录。但是我无法弄清楚如何做到这一点。

以下是我现在的查询:

SELECT DISTINCT
    products.id,
    sku,
    name,
    mediaid
FROM
    products
INNER JOIN 
    productmedia ON products.id = productmedia.productid
WHERE
    sku IN ('HCFL 207 23 (A)','HCFL 207 22 (A)','HCFL 207 21 (A)','HCFL 207 20 (A)')
    AND productmedia.sort = 100 

我得到以下内容:

183816  HCFL 207 20 (A) HCFL SERIES- 2-BOLT FLANGE, ECCENTRIC LOCKING COLLAR, BORE DIA. 1 1/4", WIDE INNER RACE INSERT -ASIAN   2929082
183816  HCFL 207 20 (A) HCFL SERIES- 2-BOLT FLANGE, ECCENTRIC LOCKING COLLAR, BORE DIA. 1 1/4", WIDE INNER RACE INSERT -ASIAN   2929083
183817  HCFL 207 21 (A) HCFL SERIES-2-BOLT FLANGE, ECCENTRIC LOCKING COLLAR, BORE DIA. 1 5/16", WIDE INNER RACE INSERT-ASIAN    2929138
183817  HCFL 207 21 (A) HCFL SERIES-2-BOLT FLANGE, ECCENTRIC LOCKING COLLAR, BORE DIA. 1 5/16", WIDE INNER RACE INSERT-ASIAN    2929139
183818  HCFL 207 22 (A) HCFL SERIES- 2-BOLT FLANGE, ECCENTRIC LOCKING COLLAR, BORE DIA. 1 3/8", WIDE INNER RACE INSERT -ASIAN   2929086
183818  HCFL 207 22 (A) HCFL SERIES- 2-BOLT FLANGE, ECCENTRIC LOCKING COLLAR, BORE DIA. 1 3/8", WIDE INNER RACE INSERT -ASIAN   2929087
183819  HCFL 207 23 (A) HCFL SERIES- 2-BOLT FLANGE, ECCENTRIC LOCKING COLLAR, BORE DIA. 1 7/16", WIDE INNER RACE INSERT -ASIAN  2929084
183819  HCFL 207 23 (A) HCFL SERIES- 2-BOLT FLANGE, ECCENTRIC LOCKING COLLAR, BORE DIA. 1 7/16", WIDE INNER RACE INSERT -ASIAN  2929085

2 个答案:

答案 0 :(得分:0)

;with cte as(
select s.id studentId, s.name, c.class, 
ROW_NUMBER() over(partition by class order by s.id) rn 
from Student s
inner join class c on s.classId = c.id
)
select * from cte where rn = 1

您可以通过s.id"更改"顺序到您认为基于订购结果的任何其他列。

答案 1 :(得分:0)

CROSS APPLY是你的朋友:

SELECT DISTINCT
    products.id,
    sku,
    name,
    mediaid
FROM
    products
    CROSS APPLY (
        SELECT TOP(1)
            * -- List the required columns!
        FROM
            productmedia
        WHERE           
            products.id = productmedia.productid
            AND productmedia.sort = 100 
        ORDER BY
            YourOrderColumn -- Change it to your required order!
    ) AS X
WHERE
    sku IN ('HCFL 207 23 (A)','HCFL 207 22 (A)','HCFL 207 21 (A)','HCFL 207 20 (A)')