Generic example.
- Convert row to JSON (
replace((SELECT t.* FOR JSON PATH),',','},{'))
and then to JSON ARRAY
[{"Id":1},{"Col1":"A"},{"Col2":"A"},{"Col3":"X"},{"Col4":"A"},{"Col5":"A"},{"Col6":"A"},{"Col7":"A"}]
- Extract RowJson values to rowset of JSON - OpenJson(RowJson) ->ColumnJson
"{"Id":1}"
"{"Col1":"A"}"
"{"Col2":"A"}"
- Extract column JSON to key-value pair. Openjson(columnJson.value)
- Specially for first (not Id) column
openjson(json_query(rowJson,'$[1]'))c1 -- column1 name and value
- Take key of first row where "value<>Column1Value" and count of columns.
Test data
CREATE TABLE test ( Id INT, Col1 VARCHAR(5), Col2 VARCHAR(5),
Col3 VARCHAR(5), Col4 VARCHAR(5), Col5 VARCHAR(5),
Col6 VARCHAR(5), Col7 VARCHAR(5));
INSERT INTO test (Id, Col1, Col2, Col3, Col4, Col5, Col6, Col7) VALUES
('1', 'A', 'A', 'X', 'A', 'A', 'A', 'A'),
('2', 'A', 'A', 'A', 'A', 'X', 'A', 'A'),
('3', 'X', 'X', 'X', 'A', 'X', 'A', 'A'),
('4', 'A', 'A', 'A', 'A', 'A', 'A', 'A');
Query
select a.id,coalesce(difcolNum,lastColnum) ConsistentColumns
from(
select id ,replace((SELECT t.* FOR JSON PATH),',','},{') rowJson
from test t
)a
cross apply (
select min(case when cast(columnJson.[key] as int)>0
and cast(KV.value as varchar(5))<>c1.[value] then cast(columnJson.[key] as int) end) difColnum
,max(cast(columnJson.[key] as int)) lastColnum
from Openjson(rowJson) as columnJson -- {"Col1":"A"},{"Col2":"A"}
cross apply Openjson(columnJson.value) as KV -- KeyValue [key]="Col3"[value]="X"
cross apply openjson(json_query(rowJson,'$[1]'))c1 -- for 1-st column KeyValue [key]="Col1"[value]="A"
)b
Fiddle
('A', 'A', null, 'A', null, 'A', 'X', ...)yield a result of 4? Should(null, 'A', 'A', 'X', ...)yield 2?(Id, WeekNo, Value)or similar?