1:当根据业务需要时,使用group by分组得到的记录,但可能还需要加上条件来对分组得到的数据进行过滤取数.可采用having的关键字来完成,具体参见以下SQL实例.
SELECT INSID,COUNT(INSID) NO_ID FROM T_WF_ENG_PROCESS GROUP BY INSID HAVING COUNT(INSID)>1;
2:关于对于字符串的一些常用处理的命令:
1):INSTR(串搜索函数)
2):REPLACE(查找并替换)
3):SUBSTR(字符串截取)
3:关于对字符串取值的一个实例:(取列名值中间一部份的值):
例1:SELECT DISTINCT REPLACE(SUBSTR(ADDRESS,INSTR(ADDRESS,'/',-1,2),(LENGTH(SUBSTR(ADDRESS,INSTR(ADDRESS,'/',-1,2),LENGTH(ADDRESS)))-LENGTH(SUBSTR(ADDRESS,INSTR(ADDRESS,'/',-1,1),LENGTH(ADDRESS))))+1),'/','') ADDRESS FROM (SELECT PAGEADDRESS ADDRESS FROM T_WF_ENG_TASKPAGE WHERE ID IN (SELECT PAGEID FROM T_WF_ENG_ACT_TASK WHERE WFID='B120-20050823' AND (KIND='G' OR KIND ='W')) UNION ALL SELECT ADDRESS FROM T_WF_ENG_LOGIN_KIND WHERE ID IN (SELECT KIND FROM T_WF_ENG_LOGIN WHERE ID IN (SELECT PAGEID FROM T_WF_ENG_ACT_TASK WHERE WFID='B120-20050823' AND KIND = 'A')) UNION ALL SELECT PATH ADDRESS FROM T_WF_ENG_AFFIX_TEMPLET WHERE ID IN (SELECT PAGEID FROM T_WF_ENG_ACT_TASK WHERE WFID='B120-20050823' AND KIND='I')) WHERE UPPER(ADDRESS) LIKE '../CUSTOM/PRIVATE/%';
例2:SELECT DISTINCT REPLACE(SUBSTR(ADDRESS,INSTR(ADDRESS,'/',-1,2),(LENGTH(SUBSTR(ADDRESS,INSTR(ADDRESS,'/',-1,2),LENGTH(ADDRESS)))-LENGTH(SUBSTR(ADDRESS,INSTR(ADDRESS,'/',-1,1),LENGTH(ADDRESS))))+1),'/','') ADDRESS FROM T_WF_ENG_XML_COMMN WHERE ADDRESS IN (SELECT PAGENAME FROM T_WF_ENG_LOGIC WHERE WFID = 'B120-20050823');
注:如果要获得某个字符串出现的次数,可使用LENGTH(ADDRESS)-LENGTH(REPLACE(ADDRESS,'_',''))这种方式获得之间的长度差即可得到出现的次数.
4:取某表的前10行数据的SQL语句:
select * from tablename where rownum<=10;
5:如果是子查询取某表的前10行数据的SQL语句可以写成如下(其中create_date字段类型必须为日期型):
select id FROM (SELECT * FROM (SELECT id, max(create_date) AS create_date FROM test WHERE status = 1 AND create_date >= sysdate - 1/24 GROUP BY id) ORDER BY create_date DESC) WHERE rownum <= 10;
说明:即然是取最新的10记录,其实是没有必要把所有的数据都group by一次的,所以可以取最近一小时的数据,做group by就可以满足需求,如果增量数据很大,也可以考虑取走分钟(5/1440)的增量数据等,通过查询条件create_date >= sysdate - 1/24,把许多不需要进行group by的记录都排除了。
也就是说,进行SQL调优时,理解SQL的意图很重要。。。
6:取月份的第一天和最后一天
SELECT LAST_DAY(ADD_MONTHS(SYSDATE,-1)) FROM DUAL;
------取上个月的最后一天.
SELECT ADD_MONTHS(LAST_DAY(ADD_MONTHS(SYSDATE,-1))+1,-1) FROM DUAL;
-----取上个月的第一天