将与数据库交互的shell脚本

时间:2010-09-29 16:26:51

标签: sql oracle bash sqlplus

一直在编写shell脚本,如:

#! /bin/bash
`sqlplus -s <username>/<passwd>@dbname`    
set echo on  
set pagesize 0  
set verify off  
set lines 32000  
set trimspool on  
set feedback off  
`SELECT tr.number, count(*) as total  
              FROM <dbname>.<tablename1> tr  
              LEFT JOIN <tablename2> t2 ON t2.id2 = tr.id1  
              LEFT JOIN <tablename3> t3 ON t3.id2 = tr.id1  
              LEFT JOIN <tablename4> t4 ON t4.id2 = tr.id1  
              WHERE tr.TIMESTAMP > SYSDATE - 75 / 1440  
               AND tr.TIMESTAMP <= SYSDATE - 15 / 1440  
              and (t2.number like '2____' OR t2.number like '3____' OR t2.number like '99____' )  
AND tr.id = 703 and t2.v1 = 100  
          group by (tr.number);`  
exit;  
EOF

目前我的输出类似于::

 tr.number                    count(*)  
 27684                        76        
 27050                         9        
 37744                         7        
 997717                       11        
 997797                        8        
 37224                         3       

我想将数字的数量分组为2_ ,3 __ ,99_ _ ,例如

tr.number  count(*)  
 2____      76+9  
 3____      7+3  
 99_____    11+8  

输出应该只有3行,起始数字为2,3和99,如上所示。

_代表4个地方。

请告知。

P.S。你能否告诉我为什么把SET操作员和他们的简要说明放在必要。

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以获取tr.number的前一个或两个字符,然后对其进行分组以获得预期结果。

由于您尚未提供表创建脚本,因此我创建了一个演示表及其数据来说明这一点。

create table tr(
   id number,
   total_records number);

insert into tr values (200123,50);
insert into tr values (20034, 25);
insert into tr values (30034, 15);
insert into tr values (300567, 100);
insert into tr values (990034, 75);
insert into tr values (990034, 80);
insert into tr values (990034, 456);
commit;


SELECT   starts_with, SUM (total_records) total_records
    FROM (SELECT ID,
                 (CASE WHEN ID LIKE '2%'  THEN '2____'
                       WHEN ID LIKE '3%'  THEN '3____'
                       WHEN ID LIKE '99%' THEN '99____'
                  END
                 ) starts_with,
                 total_records
            FROM tr
            where ( id like '2%' or id like '3%' or id like '99%'))
GROUP BY starts_with;

STARTS TOTAL_RECORDS
------ -------------
2____             75
3____            115
99____           611

答案 1 :(得分:1)

您可以在手册中看到SET命令的作用:http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch12040.htm

答案 2 :(得分:0)

感谢Rajesh,

现在,如果total_records等于0,我必须通过电子邮件将输出发送到脚本中的特定电子邮件地址。该电子邮件应该还有主题和正文。