简体   繁体   中英

How to get database columns from more than one table in sql server and then group by table name

I have a scenario in which I want to fetch database table columns from two tables and then I want to group by table name,

eg

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.columns
WHERE table_name='lead' 
UNION ALL
SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.columns
WHERE table_name='CustomQuestion'  
GROUP BY

在此处输入图片说明

Why group, you have no aggregate? I think you mean ORDER BY

select TABLE_NAME, COLUMN_NAME
from INFORMATION_SCHEMA.columns
where TABLE_NAME in ('CustomQuestion','lead')
order by TABLE_NAME, COLUMN_NAME

Based on comments, what you're asking for (table name to appear only once) is really more reporting functionality than query functionality; which is to say there's probably better ways to do it than wedge it into SQL.

But that doesn't mean you can't wedge it into SQL, so here you go:

select case when row_number() over(partition by table_name 
                                       order by column_name) = 1
            then TABLE_NAME
            else ''
       end as TABLE_NAME
     , COLUMN_NAME
  from INFORMATION_SCHEMA.columns
 where TABLE_NAME in ('CustomQuestion','lead')
 order by TABLE_NAME, COLUMN_NAME

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