SQL查询获取第一个记录

时间:2017-11-02 06:31:08

标签: sql sql-server

这是我的SQL查询:

SELECT 
    TM09_Product.F09_ProductCode, TX42_KndCmd.F42_KndCmdNo,   
    TX42_KndCmd.F42_PreProductCode
FROM 
    TX42_KndCmd 
INNER JOIN 
    TM09_Product ON TX42_KndCmd.F42_PreProductCode = TM09_Product.F09_PreProductCode
GROUP BY 
    TX42_KndCmd.F42_PreProductCode, TM09_Product.F09_ProductCode, 
    TX42_KndCmd.F42_KndCmdNo
ORDER BY 
    TX42_KndCmd.F42_PreProductCode

查询结果如下:

F09_ProductCode  F42_KndCmdNo  F42_PreProductCode
-------------------------------------------------
    1B28G048        A01257       1A1EP0000090
    1B28G048        A01914       1A1EP0000090
    1B28G048        A02283       1A1EP0000090
    1B28G048A       A01257       1A1EP0000090
    1B28G048A       A01914       1A1EP0000090
    1B28G048A       A02283       1A1EP0000090
    1B28G048B       A01257       1A1EP0000090
    1B28G048B       A01914       1A1EP0000090
    1B28G048B       A02283       1A1EP0000090

似乎不断重复同一组值。在这种情况下,我只想显示每组F09_ProductCode的第一条记录。

预期结果应显示:

F09_ProductCode  F42_KndCmdNo  F42_PreProductCode
-------------------------------------------------
    1B28G048        A01257       1A1EP0000090
    1B28G048A       A01257       1A1EP0000090
    1B28G048B       A01257       1A1EP0000090

任何人都可以指导我应该做出哪些改变或研究? 感谢。

1 个答案:

答案 0 :(得分:1)

您可以通过F09_ProductCode功能为Row_Number()分配排名: -

SELECT *
FROM
(
    SELECT *,
           ROW_NUMBER() OVER(PARTITION BY A.F09_ProductCode ORDER BY
                            (
                                SELECT NULL
                            )) RN
    FROM
    (
        SELECT TM09_Product.F09_ProductCode,
               TX42_KndCmd.F42_KndCmdNo,
               TX42_KndCmd.F42_PreProductCode
        FROM TX42_KndCmd
             INNER JOIN TM09_Product ON TX42_KndCmd.F42_PreProductCode = TM09_Product.F09_PreProductCode
        GROUP BY TX42_KndCmd.F42_PreProductCode,
                 TM09_Product.F09_ProductCode,
                 TX42_KndCmd.F42_KndCmdNo
--ORDER BY TX42_KndCmd.F42_PreProductCode

    ) A
) AA
WHERE AA.RN = 1;

结果:

F09_ProductCode F42_KndCmdNo  F42_PreProductCode  RN
1B28G048        A01257        1A1EP0000090        1
1B28G048A       A01257        1A1EP0000090        1
1B28G048B       A01257        1A1EP0000090        1