Sql 表示值组中的最小日期的新列
我想添加一个新的列,它将指示子组的最小值Sql 表示值组中的最小日期的新列,sql,sql-server,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 122
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的最小OrderDate,我想将“1”分配给此ShopId。尝试以下操作:
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
,ShopId
)的最小值。如果这两个值相同,那么我们将相应的(Id
,ShopId
)分区标记为1
没有其他的优雅,但是是ANSI
select MyTable.*, case when a1.mindate = orderdate then 1 else 0 end as NewCol
from MyTable
inner join
(
select id, min(orderdate) as mindate
from Mytable
group by id
) a1
on a1.id = MyTable.id
您可以使用带窗口功能的min来获得如下结果:
select NewCol = Case when orderdate = min(orderdate) over() then 1 else 0 end,*
from yourtable
--您可能需要根据需求添加按Id或shopId划分的分区使用
min
和shopId上的orderdate,并在以下语句中使用该选项:-
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;
试试这个
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
第二行OrderDate值是否正确?@maSTAShuFu:是的,我尝试过,但只使用了rank函数,但这不是我所期望的。请随意将您尝试的查询包含在您的问题中。然后我们可以看到哪里出了问题,并为您指出正确的方向。