简体   繁体   中英

Count data from one table where table column = row number

How do I use SQL query to count in table t where column1 or column2 or column3 or column 4 = row numbers. example

Table t

c1  c2  c3  c4   c5  c6
 2   4   7  10  22  35
 1   3   7  22  35  39
 1   2   21 30  35  36

Result

RowNumbe  count
1           2
2           2
3           1
4           1
5           0
6           0
7           2
8           0
9           0
10          1 etc

You can use do left join with union sub-query :

select seq.RowNumber, count(cols.col) as cnt
from ( select 1 as RowNumber union all
       select 2 union all
       . . . 
       select 10
     ) as seq left join
     ( select t.col1 as col
       from table t union all
       select t.col2
       from table t union all
       . . .
       select t.col6
       from table t
     ) as cols
     on seq.RowNumber = cols.col
group by seq.RowNumber

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM