我目前有一个非常简单的查询,可以简单地选择并生成以下内容
| Date | Name | ID |
|------------|------------------|---------|
| 2018-11-07 | McDonald's | 1046226 |
| 2018-01-22 | NULL | 1046226 |
| 2019-01-07 | Dell | 1069285 |
| 2019-01-09 | Dell Corporation | 1069285 |
我想做的是使用MIN为每个ID选择最早的日期行
但是我的问题是,如果最早的行名称为NULL,我想从另一行合并其名称
| Date | Name | ID |
|------------|------------------|---------|
| 2018-01-22 | McDonald's | 1046226 |
| 2019-01-07 | Dell | 1069285 |
我不知道是否有任何语法可以在这里帮助我,有人可以帮助吗?
答案 0 :(得分:1)
使用coalesce
:
select
min(t.date) Date,
coalesce(
(
select name from tablename where id = t.id and date = (
select min(date) from tablename where id = t.id
)
),
max(name)
) name,
t.id ID
from tablename t
group by t.id
答案 1 :(得分:0)
通常,row_number()
用于此目的:
select t.*
from (select t.*, row_number() over (partition by id order by date) as seqnum
from <your query here> t
) t
where seqnum = 1;
一种稍微慢一点的简单方法是:
select top (1) with ties . . .
from . . .
. . .
order by row_number() over (partition by id order by date)
答案 2 :(得分:0)
使用CTE在Azure SQL数据仓库上测试的两种方法
import { FormsModule, ReactiveFormsModule } from "@angular/forms"; //this to use ngModule
或者,如果您要将剩余数据CTAS到新表中,则可以在Azure SQL数据仓库中将CTE和CTAS结合起来,例如
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
FormsModule,
RouterModule,
ReactiveFormsModule,
BrowserAnimationsModule,
MaterialModule],
请注意;WITH cte AS
(
SELECT *, ROW_NUMBER() OVER( PARTITION BY ID ORDER BY [Date] ) rn
FROM #tmp
)
SELECT [Date], name, ID
FROM cte
WHERE rn = 1
和CREATE TABLE dbo.yourNewTable
WITH
(
CLUSTERED COLUMNSTORE INDEX,
DISTRIBUTION = HASH( ID )
-- Optionally add partition scheme here if required
)
AS
WITH cte AS
(
SELECT
[Date],
MIN(Name) OVER( PARTITION BY ID ) name,
ID,
ROW_NUMBER() OVER( PARTITION BY ID ORDER BY [Date] ) rn
FROM dbo.yourTable
)
SELECT [Date], name, ID
FROM cte
WHERE rn = 1
OPTION ( LABEL = 'CTAS : Dedupe' );
在行为上的差异。