Transact-SQL] [number of occurrences of the whole table of all the values

Original: [] Transact-SQL whole number of occurrences of all the values in the table

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.

 


   
   
  1. if(OBJECT_ID('dbo.wc') is not null)
  2. drop table dbo.wc
  3. go
  4. create table wc
  5. (
  6. a nvarchar( 100),
  7. b nvarchar( 100),
  8. c nvarchar( 100)
  9. )
  10. insert into wc
  11. values( '1', '2', '3'),
  12. ( 'a', 'f', 'd'),
  13. ( '2', 'b', 'c'),
  14. ( null, 'c', 'w'),
  15. ( '3', 'd', null)
  16. declare @temp table (cn nvarchar( 100));
  17. declare @i int = 1;
  18. declare @v varchar( max)= '';
  19. declare @ column varchar( 100)= '';
  20. while @i <= (
  21. select count(*)
  22. from sys.tables t
  23. inner join sys.columns c
  24. on t.object_id =c.object_id
  25. where t.name = 'wc'
  26. )
  27. begin
  28. select @ column = c.name
  29. from sys.tables t
  30. inner join sys.columns c
  31. on t.object_id =c.object_id
  32. where t.name = 'wc'
  33. and c.column_id = @i
  34. set @i = @i + 1
  35. set @v = @v + ' select '+ @ column + ' from wc union all'
  36. end
  37. select @v = LEFT(@v, len(@v)- LEN( 'union all'))
  38. --select @v
  39. insert into @temp
  40. exec (@v)
  41. ;with a
  42. as
  43. (
  44. select cn
  45. from @temp
  46. where cn is not null
  47. group by cn
  48. )
  49. select a.cn,
  50. COUNT(t.cn)
  51. from a
  52. inner join @temp t
  53. on a.cn = t.cn
  54. group by a.cn


 

Published 416 original articles · won praise 135 · views 940 000 +

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12019940.html