我有一個回傳表的查詢,基于值(如果存在),我想設定行數。 我有一些解決方案,但它看起來很長,我認為可以更容易和更少的代碼(最佳選擇)來處理它。下面是預期結果的例子:
如果查詢的結果是 "行數",那么就會有 "行數"。
如果查詢回傳客戶端為NULL: OutPut應該是: 如果查詢沒有回傳NULL: OutPut應該是: uj5u.com熱心網友回復: uj5u.com熱心網友回復: ... uj5u.com熱心網友回復: 我不確定 哦,我明白了,你不是將
標籤:----------------------。
程序| 客戶|
A | NULL |
A |B |
A |B |
A |B |
A | C |
A | C | 2.
A | C |
----------------------
程序| 客戶| RowNumber
A | NULL | 1 流程
A | B | 2
A | B | 3
A |B | 4
A | C | 2
A | C | 3
A | C | 4
----------------------
程序| 客戶|
A | B |
A |B |
A |B |
A | C |
A | C | 2.
A | C |
----------------------
程序| Client| RowNumber
A | B | 1
A | B | 2
A | B | 3
A | C | 1
A | C | 2
A | C | 3
。
DROP TABLE if exists mytable;
CREATE TABLE mytable(Process char(1), 客戶 char(1))。
INSERT INTO mytable values
('A',null) 。
('A','B') 。
('A','B')。
('A','B')。
('A','C')。
('A','C')。
('A','C')。
--有一個NULL值。
選中
流程。
客戶端。
ROW_NUMBER() OVER (partition by process。 客戶端 order by (select null)) CASE WHEN 客戶is null THEN 0 else 1 end R
from mytable;
--不含空值
selectROW_NUMBER() OVER (partition by process。 客戶 order by (select null) R
from mytable
where not client is null;
declare @t table(process varchar(10) 。客戶 varchar(10))。
insert into @t(行程,客戶端
values(process, client)
('A', null) 。
('A', 'B'),('A', 'B'), ('A', 'B')。
('A', 'C'), ('A', 'C') 。
('A', ''), ('A', '') 。('A', ' '), ('A', ' ') 。
('A', 'ZXY'), ('A', 'ZXY') 。
('X', 'B'),('X', 'B'), ('X', 'B') 。
('X', 'C'), ('X', 'C') 。
select *,
row_number() over(partition by process, 客戶端 order by client)
--如果每個行程有一個空客戶,那么就給每個非空客戶加1。
case when client is not null and min(case when client is null then 0 else 1 end) over(partition by process) = 0 then 1 else 0 end
-- case when client is not null and min(isnull(ASCII(client '.), 0)) over(partition by process) = 0 then 1 else 0 end
as rownumber
來自的
(
select *
from @t
-- where client is not null
) as t。
NULL是否應該總是被視為'B',但你需要處理:select t.* ,
row_number() over (partition by process, coalesce(client, 'B') order by (selectnull)
from t
where client is not null;
NULL設定為'B',而是將NULL的數量添加到其他值中。 這也是很簡單的:select t.* ,
(row_number() over (partition by processes, 客戶端 order by (select null)) (select)
(case when client is null then 0else sum(case when client is null then 1 else 0 end) over ( )
end)
)
from t
where client is not null;
