1

我在让 TOP 在我的 SQL 查询中工作时遇到问题。我只想查看 PART_AML 表中的第一行。我没有任何运气尝试只查询该表而不查询 PART 表。

我怎样才能只显示 PART_AML 表中的第一行?我正在使用 Microsoft SQL。

感谢您的帮助,非常感谢。

SELECT  innovator.PART.STATE, 
    innovator.PART.NAME, 
    innovator.PART.ITEM_NUMBER, 
    innovator.PART.ID, 
    innovator.PART.TYPE, 
    innovator.MANUFACTURER_PART.SPEC_URL

FROM innovator.PART     

join innovator.PART_AML
    on innovator.PART_AML.SOURCE_ID = innovator.PART.ID

join innovator.MANUFACTURER_PART
    on innovator.MANUFACTURER_PART.ID = innovator.PART_AML.RELATED_ID

WHERE
(innovator.PART.IS_CURRENT = 1) AND (innovator.PART_AML.IS_CURRENT = 1) AND (innovator.MANUFACTURER_PART.IS_CURRENT = 1) 

电流输出

    Number  Name        ID      Type        Spec
    E000836 1k          ID1     Resistor    SPEC 1
    E000836 1k          ID1     Resistor    SPEC 2
    E000836 1k          ID1     Resistor    SPEC 3
    E003455 14.400MHz   ID2     Crystal     SPEC 1
    E003455 14.400MHz   ID2     Crystal     SPEC 2
    E003455 14.400MHz   ID2     Crystal     SPEC 3

首选输出

    Number  Name        ID      Type        Spec
    E000836 1k          ID1     Resistor    SPEC 1
    E003455 14.400MHz   ID2     Crystal     SPEC 1
4

2 回答 2

2

您可以使用排名功能ROW_NUMBER() OVER(ORDER BY ...)来做到这一点:

WITH CTE
AS
(
    SELECT  
      i.STATE, 
      i.NAME, 
      i.ITEM_NUMBER, 
      i.ID, 
      i.TYPE, 
      p.SPEC_URL,
      ROW_NUMBER() OVER(PARTITION BY i.ID
                        ORDER BY p.SPEC_URL) AS Rownum
    FROM innovator.PART AS i
    INNER JOIN innovator.PART_AML          AS a on a.SOURCE_ID = i.ID
    INNER JOIN innovator.MANUFACTURER_PART AS p on p.ID        = a.RELATED_ID
    WHERE i.IS_CURRENT = 1 
      AND a.IS_CURRENT = 1
      AND p.IS_CURRENT = 1
)
SELECT *
FROM CTE
WHERE rownum = 1;
于 2013-03-15T15:18:13.303 回答
0

您也可以使用带有 MIN() 函数的简单GROUP BY子句

SELECT innovator.PART.STATE, 
       innovator.PART.NAME, 
       innovator.PART.ITEM_NUMBER, 
       innovator.PART.ID, 
       innovator.PART.TYPE, 
       MIN(innovator.MANUFACTURER_PART.SPEC_URL) AS SPEC_URL
FROM innovator.PART join innovator.PART_AML on innovator.PART_AML.SOURCE_ID = innovator.PART.ID
                    join innovator.MANUFACTURER_PART on innovator.MANUFACTURER_PART.ID = innovator.PART_AML.RELATED_ID
WHERE (innovator.PART.IS_CURRENT = 1) AND (innovator.PART_AML.IS_CURRENT = 1) AND (innovator.MANUFACTURER_PART.IS_CURRENT = 1)
GROUP BY innovator.PART.STATE, innovator.PART.NAME, innovator.PART.ITEM_NUMBER, innovator.PART.ID, innovator.PART.TYPE  
于 2013-03-15T15:53:23.240 回答