# 如何选择组中每列的最后一个非NULL值集？

9

``````CREATE TABLE #tab (cat CHAR(1), t CHAR(2), val1 INT, val2 CHAR(1));

INSERT INTO #tab VALUES
('A','Q1',2,NULL),('A','Q2',NULL,'P'),('A','Q3',1,NULL),('A','Q3',NULL,NULL),
('B','Q1',5,NULL),('B','Q2',NULL,'P'),('B','Q3',NULL,'C'),('B','Q3',10,NULL);

SELECT *
FROM    #tab;
``````

``````cat  val1 val2
A    1    P
B    10   C
``````

``````SELECT DISTINCT
cat,
LAST_VALUE(val1) OVER(PARTITION BY cat ORDER BY (SELECT NULL) ) AS val1,
LAST_VALUE(val2) OVER(PARTITION BY cat ORDER BY (SELECT NULL) ) AS val2
FROM    #tab
``````
``````cat  val1 val2
A    NULL NULL
B    10   NULL
``````

1
@Vérace按`cat`排序`t`
Edmund

1
@ypercubeᵀᴹ不，没有缺失的Q4值，这些`t`值重复出现。它不是行为良好的数据。
Edmund

4

ypercubeᵀᴹ

1
@ypercubeᵀᴹ挑战就在其中。数据中没有id列。有多个分组列，一个可用于组排序的字符串列，然后是多个散有null的值列。
Edmund

1

10

``````select T.cat,
cast(substring(
max(cast(T.t as binary(2)) + cast(T.val1 as binary(4))),
3,
4
) as int),
cast(substring(
max(cast(T.t as binary(2)) + cast(T.val2 as binary(1))),
3,
1
) as char(1))
from #tab as T
group by T.cat;
``````

``````with C1 as
(
-- Concatenate the ordering column with the value column
select T.cat,
cast(T.t as binary(2)) + cast(T.val1 as binary(4)) as val1,
cast(T.t as binary(2)) + cast(T.val2 as binary(1)) as val2
from #tab as T
),
C2 as
(
-- Get the max concatenated value per group
select C1.cat,
max(C1.val1) as val1,
max(C1.val2) as val2
from C1
group by C1.cat
)
-- Extract the value from the concatenated column
select C2.cat,
cast(substring(C2.val1, 3, 4) as int) as val1,
cast(substring(C2.val2, 3, 1) as char(1)) as val2
from C2;
``````

。– pimbrouwers

2

``````SELECT DISTINCT
cat,
FIRST_VALUE(val1) OVER(PARTITION BY cat ORDER BY CASE WHEN val1 is NULL then 0 else 1 END DESC, t desc) AS val1,
FIRST_VALUE(val2) OVER(PARTITION BY cat ORDER BY CASE WHEN val2 is NULL then 0 else 1 END DESC, t desc) AS val2
FROM    #tab
``````

0

``````declare @t TABLE (cat CHAR(1), t CHAR(2), val1 INT, val2 CHAR(1));
INSERT INTO @t VALUES
('A','Q1',2,NULL),('A','Q2',NULL,'P'),('A','Q3',1,NULL),('A','Q3',NULL,NULL),
('B','Q1',5,NULL),('B','Q2',NULL,'P'),('B','Q3',NULL,'C'),('B','Q3',10,NULL);

--SELECT *
--     , row_number() over (partition by cat order by t) as rn
--FROM   @t
--where val1 is not null or val2 is not null;

select t1.cat, t1.val1, t2.val2
from  ( SELECT t.cat, t.val1
, row_number() over (partition by cat order by t desc) as rn
FROM   @t t
where val1 is not null
) t1
join   ( SELECT t.cat, t.val2
, row_number() over (partition by cat order by t desc) as rn
FROM   @t t
where val2 is not null
) t2
on t1.cat = t2.cat
and t1.rn = 1
and t2.rn = 1
``````
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.