新列,表示从值组中的最小日期

时间:2017-05-22 10:30:33

标签: sql sql-server

我想添加一个新列,它将指示子组的最小值。

Id          ShopId      OrderDate
12232018    12229018    2011-01-01 00:00:00.000
12232018    12229018    2012-01-01 00:00:00.000
12232018    12394018    2012-02-02 00:00:00.000
12232018    11386005    2012-03-01 00:00:00.000
12232018    14347023    2012-04-02 00:00:00.000
12232018    14026026    2014-03-16 00:00:00.000

以下是我想得到的结果:

NewCol    Id        ShopId      OrderDate
1         12232018  12229018    2011-01-01 00:00:00.000
1         12232018  12229018    2012-01-01 00:00:00.000
0         12232018  12394018    2012-02-02 00:00:00.000
0         12232018  11386005    2012-03-01 00:00:00.000
0         12232018  14347023    2012-04-02 00:00:00.000
0         12232018  14026026    2014-03-16 00:00:00.000

因为ShopId有Id最小订单日期我想分配' 1'到这个ShopId。

5 个答案:

答案 0 :(得分:1)

你可以使用min和窗口函数来实现如下:

select NewCol = Case when orderdate = min(orderdate) over() then 1 else 0 end,*
    from yourtable

- 可能您可能需要按ID添加分区或shopId取决于要求

答案 1 :(得分:0)

试试这个:

SELECT Id, ShopId, OrderDate,
       CASE 
          WHEN MIN(OrderDate) OVER (PARTITION BY Id, ShopId) = 
               MIN(OrderDate) OVER (PARTITION BY Id) THEN 1
          ELSE 0
       END AS NewCol
FROM mytable

该查询使用MAX的窗口版本,以便将最低每Id OrderDate与最低 - (Id,{{1}进行比较})约会。如果这两个值相同,那么我们用1标记相应的(ShopIdId)分区。

Demo here

答案 2 :(得分:0)

不如其他人优雅,但是ANSI

SELECT m.id, m.msg_body, m.creator_id, mr.recipient_id
FROM message m 
JOIN message_recipient mr on m.id=mr.id
WHERE m.creator_id='1' AND mr.recipient_id='2'

答案 3 :(得分:0)

在ShopId上使用带有orderdate的min并在Case When语句中使用它,如下所示: -

Select case when (a.OrderDate=b.min_order_dt) then 1 else 0 end as NewCol, a.*
from
your_table_name a
inner join
(
SELECT ShopId, min(OrderDate) as min_order_dt
from
your_table_name
group by shop_id
) b
on a.ShopId=b.ShopId;

答案 4 :(得分:0)

试试这个

select case when t2.ShopId is null then 0 else 1 end  as newcol,t1.id,
t1.ShopiId,t1.OrderDate 
from table as t1 left join
(
select ShopId,min(OrderDate) as OrderDate from table
group by ShopId
) as t2 on t1.ShopId=t2.ShopId and t1.OrderDate=t2.OrderDate