多表select count语句生成 带格式化

#!/bin/sh

max_length=0
for table_name in `cat tables`
do
    current_length=$(echo ${table_name}|wc -c)
    if [ ${current_length} -gt ${max_length} ]
    then
        max_length=${current_length}
    fi
done
max_length=$((${max_length}-1))

printf "select *\n"
printf "from (\n"
cat tables|while read table_name
do
    printf "    select '%-${max_length}s' as table_name,count(1) as cnt from %-${max_length}s union all\n" ${table_name} ${table_name} 
done
printf "    select '%-${max_length}s' as table_name,count(1) as cnt\n" "invaild_column"
printf ") t1\n"
printf "where table_name <> 'invaild_column'\n"
printf "order by table_name\n"
printf ";\n"
select *
from (
    select 'table_01 ' as table_name,count(1) as cnt from table_01  union all
    select 'table_02 ' as table_name,count(1) as cnt from table_02  union all
    select 'table_03 ' as table_name,count(1) as cnt from table_03  union all
    select 'invalid_column' as table_name,count(1) as cnt
) t1
where table_name <> 'invalid_column'
order by table_name
;
posted @ 2020-12-22 14:51  chenzechao  阅读(221)  评论(0编辑  收藏  举报