A table with 3, 5 rows, a total of 15 values, now want to calculate the number of the entire table all values appear in the table, but the number of columns in the table here is uncertain, the above example is 3, the actual on there may be 5, 20, so the steps to solve the problem is this:
1, you must know how many columns, then construct a dynamic statement, to merge into one in these columns.
2, and then to re-calculate all possible values.
3, the final calculation of how many times each value appears in the table.
-
if(OBJECT_ID('dbo.wc') is not null)
-
drop
table dbo.wc
-
go
-
-
-
create
table wc
-
(
-
a
nvarchar(
100),
-
b
nvarchar(
100),
-
c
nvarchar(
100)
-
)
-
-
insert
into wc
-
values(
'1',
'2',
'3'),
-
(
'a',
'f',
'd'),
-
(
'2',
'b',
'c'),
-
(
null,
'c',
'w'),
-
(
'3',
'd',
null)
-
-
-
declare @temp
table (cn
nvarchar(
100));
-
-
declare @i
int =
1;
-
-
declare @v
varchar(
max)=
'';
-
-
declare @
column
varchar(
100)=
'';
-
-
while @i <= (
-
select
count(*)
-
from sys.tables t
-
inner
join sys.columns c
-
on t.object_id =c.object_id
-
where t.name =
'wc'
-
)
-
begin
-
select @
column = c.name
-
from sys.tables t
-
inner
join sys.columns c
-
on t.object_id =c.object_id
-
where t.name =
'wc'
-
and c.column_id = @i
-
-
set @i = @i +
1
-
-
set @v = @v +
' select '+ @
column +
' from wc union all'
-
-
end
-
-
select @v =
LEFT(@v,
len(@v)-
LEN(
'union all'))
-
--select @v
-
-
insert
into @temp
-
exec (@v)
-
-
;with a
-
as
-
(
-
select cn
-
from @temp
-
where cn
is
not
null
-
group
by cn
-
)
-
-
select a.cn,
-
COUNT(t.cn)
-
from a
-
inner
join @temp t
-
on a.cn = t.cn
-
group
by a.cn