在不使用TOP 1的情况下获取列的第一个值

时间:2018-10-23 23:28:13

标签: sql sql-server tsql

我有一个表,其中有此列

+------------+-----------+
| ProjectKey | DesignKey |
+------------+-----------+
|       3978 |      6352 |
|       3978 |      6353 |
|       3978 |      6354 |
+------------+-----------+

我只想获得一个项目密钥的第一个designkey,所以我尝试:

SELECT DISTINCT* FROM PROJECTDESIGN WHERE PROJECTKEY = 3978 

但是它会返回所有行

我也尝试:

SELECT * FROM PROJECTDESIGN WHERE PROJECTKEY = 3978 GROUP BY ProjectKey, DesignKey

但是它仍然返回所有行

我需要做的只是不使用TOP 1仅获得第一行。我想要没有TOP 1,因为这只是一个例子,我的表可以有多个ProjectKey,所以不要像这样:

+------------+-----------+
| ProjectKey | DesignKey |
+------------+-----------+
|       3978 |      6352 |
|       3978 |      6353 |
|       3978 |      6354 |
|       4000 |      2568 |
|       4000 |      2590 |
|       3000 |      6600 |
+------------+-----------+

我的愿望结果是:

+------------+-----------+
| ProjectKey | DesignKey |
+------------+-----------+
|       3978 |      6352 |
|       4000 |      2568 |
|       3000 |      6600 |
+------------+-----------+

4 个答案:

答案 0 :(得分:5)

以下是使用row_number的一种选择:

select *
from (
    select *, row_number() over (partition by projectkey order by designkey) rn
    from projectdesign
) t
where rn = 1

答案 1 :(得分:1)

您似乎只希望每组最少数量

select ProjectKey, min(DesignKey) as "FirstDesignKey"
from ProjectDesign
group by ProjectKey;

答案 2 :(得分:0)

这是仅获取每个ProjectKey的最小DesignKey的另一种选择

DECLARE @Project TABLE
    (
        [ProjectKey] BIGINT
      , [DesignKey] BIGINT
    );

INSERT INTO @Project (
                         [ProjectKey]
                       , [DesignKey]
                     )
VALUES ( 3978, 6352 )
     , ( 3978, 6353 )
     , ( 3978, 6354 )
     , ( 4000, 2568 )
     , ( 4000, 2590 )
     , ( 3000, 6600 );

SELECT DISTINCT [ProjectKey]
              , MIN([DesignKey]) OVER ( PARTITION BY [ProjectKey] ) AS [DesignKey]
FROM   @Project;

答案 3 :(得分:0)

尝试时,您应该只有GROUP BY拥有ProjectKey 然后DesignKey就可以视为min(DesignKey)

(我假设您希望每个DesignKey都获得ProjectKey的小额收益-您预期的结果是否合适)

SELECT
    ProjectKey,
    min(DesignKey) as DesignKey
FROM
    PROJECTDESIGN
GROUP BY
    ProjectKey

您还可以采用任何(更复杂的)方式使用DesignKeycross apply会有所帮助:

select
    A.ProjectKey,
    B.DesignKey
from
    (select distinct ProjectKey from PROJECTDESIGN) A
    cross apply
    (
        select top 1 DesignKey from PROJECTDESIGN B
        where A.ProjectKey = B.ProjectKey
        order by DesignKey asc
    ) B

这里cross apply将尝试为表A中每个不同的ProjectKey填充一行。 它产生的效果与以前的示例相同,但是在其中您可以找到更为复杂的条件。订单栏可以更改。