如何用最大值标记行

时间:2019-02-13 17:05:55

标签: sql sql-server

我有一个ID,用于标识我的每一行,商品ID,供应商ID和库存。

+----+------------+-------------+-------+
| ID | article_ID | supplier_ID | stock |
+----+------------+-------------+-------+
| 1  | 1          | 1           | 18    |
| 2  | 1          | 2           | 1     |
| 3  | 1          | 3           | 20    |
| 4  | 2          | 1           | 5     |
| 5  | 2          | 2           | 40    |
| 6  | 3          | 1           | 56    |
| 7  | 3          | 3           | 7     |
| 8  | 3          | 4           | 12    |
+----+------------+-------------+-------+

我需要标记提供最大库存的供应商,并得到以下结果:

+----+------------+-------------+-------+------+
| ID | article_ID | supplier_ID | stock | flag |
+----+------------+-------------+-------+------+
| 1  | 1          | 1           | 18    | 0    |
| 2  | 1          | 2           | 1     | 0    |
| 3  | 1          | 3           | 20    | 1    |
| 4  | 2          | 1           | 5     | 0    |
| 5  | 2          | 2           | 40    | 1    |
| 6  | 3          | 1           | 56    | 1    |
| 7  | 3          | 3           | 7     | 0    |
| 8  | 3          | 4           | 12    | 0    |
+----+------------+-------------+-------+------+

我对问题的理解是,我需要从一个标识最大库存值行ID的选择中进行选择,但是我不知道该怎么去。 我被困住了……需要您的帮助stackoverflow的骑士!

3 个答案:

答案 0 :(得分:2)

使用窗口功能:

select t.*,
       (case when stock = max(stock) over (partition by article_id)
             then 1 else 0
        end) as flag
from t;

注意:如果所有供应商的最大值都相同,则这将标记多个供应商。如果只需要一个,请使用row_number()

select t.*,
       (case when row_number() over (partition by article_id order by stock desc) = 1
             then 1 else 0
        end) as flag
from t;

答案 1 :(得分:2)

您也可以使用APPLY

SELECT t.*, (CASE WHEN t.stock = t1.maxstock THEN 1 ELSE 0 END) AS flag
FROM table t CROSS APPLY
     (SELECT MAX(t1.stock) as maxstock 
      FROM table t1
      WHERE t1.article_id = t.article_id
     ) t1;

答案 2 :(得分:-2)

我认为这会对您有所帮助。

                create table #temp

            (
            ID int,
            article_ID int,
            supplier_ID int,
            stock int
            )

            insert into #temp values (1  , 1 , 1, 18)
            insert into #temp values (2  , 1          , 2           , 1    )
            insert into #temp values (3  , 1          , 3           , 20   )
            insert into #temp values (4  , 2          , 1           , 5    )
            insert into #temp values (5  , 2          , 2           , 40   )
            insert into #temp values (6  , 3          , 1           , 56   )
            insert into #temp values (7  , 3          , 3           , 7    )
            insert into #temp values (8  , 3          , 4           , 12   )



            Select ID,article_ID,supplier_ID,stock,case when Stock >= 20 Then 1 Else 0 End As Flag from #temp

            Drop table #temp

enter image description here