假设我有表A,B,C,......,Z
,并且我想对表中的所有条目进行计数并按以下方式合并结果:
SELECT 'A' AS A, count(*) from USER.A UNION
.
.
.
SELECT 'J' AS J, count(*) from USER.J UNION
.
.
SELECT 'Z' AS 'Z' COUNT(*) from USER.Z
我想避免上述所有麻烦。我该如何以一种聪明的方式做到这一点?
答案 0 :(得分:2)
我倾向于通过使用node* invert(node* list)
{
node* inverted = NULL;
// run through original in order
for (node* p = list; p != NULL; p = p->next)
{
// clone the node
node* newNode = new node();
newNode->num = p->num;
// and link it so that the predecessor in the original list
// (which has been processed in the previous iteration) is
// linked as next node
newNode->next = inverted;
inverted = newNode;
}
return inverted;
}
元信息视图编写查询并首次选择实际上是sql查询的文本来做到这一点:
user_tables
在查询工具中运行该行将产生一行网格,实际上它们本身就是sql查询。将它们复制到结果网格之外,粘贴到查询窗口中(删除尾随的UNION ALL),然后再次运行它们,将为每个表生成数据
SELECT 'select '''||TABLE_NAME||''', count(*) from '||TABLE_NAME||'union all' FROM USER_TABLES
要更深入地参与并包括列名,有一个USER_TAB_COLUMNS视图引用了有关列的信息(例如,您可以编写一个查询来生成查询,该查询可以搜索任何varchar列以获取特定值)
如果您真的参与其中,那么在字符串中使用占位符并替换它们会更干净:
select 'a', count(*) from a union all
select 'b', count(*) from b union all ....
这比使用||始终启动和停止字符串要干净得多。级联。我故意在外部查询中使用大写字母,在内部查询中使用小写字母,以便您可以知道哪一部分是哪一个
要添加更多的占位符,请在顶部放置其他REPLACE(,然后将粘贴复制并粘贴到下面以逗号开头的行中。示例复制SELECT REPLACE(REPLACE(REPLACE(
'select ''{o}.{t}'' as tname, ''{c}'' as cname
from {o}.{t} where
{c} like ''hello%'' or
{c} like ''goodbye%'' union all'
--to add more placeholders copy paste these lines
--and ensure there is the same number of REPLACE
--as there are numbers of lines
, '{t}', TABLE_NAME)
, '{c}', COLUMN_NAME)
, '{o}', OWNER)
FROM ALL_TAB_COLUMNS
WHERE DATA_TYPE = 'VARCHAR'
粘贴并更改为, '{t}', table_name)
并添加另一个{{1 }}顶部,现在有了{d}占位符,您可以在第一个字符串(sql查询模式)的任何地方使用它来表示数据类型