DB2数据库查询

好记性不如写一遍,复习用
1:普通查询
SELECT
    THIRDSYSTIME AS 交易时间,AMOUNT  AS 交易金额,AUTHORCODE  AS 交易码, FEE  AS 手续费,SYSSERNO AS 系统跟踪号
FROM T_CPS_CUPSICACINFO;

DB2数据库查询_第1张图片
2:筛选查询
SELECT
    THIRDSYSTIME AS 交易时间,AMOUNT  AS 交易金额,AUTHORCODE  AS 交易码, FEE  AS 手续费,SYSSERNO AS 系统跟踪号
FROM T_CPS_CUPSICACINFO
WHERE  AMOUNT>=900.00

DB2数据库查询_第2张图片

筛选查询主要有:

=【等于】

!=<>【不等于】

>【大于】

<【小于】

>=【大于等于】

<=【小于等于】

3:特殊关键字筛选

Likenot like;innot in;between...andnot between...and;is nullnot is null

Like【模糊查询】

_:代表一个字符;

%:代表任意个字符

SELECT
    THIRDSYSTIME AS 交易时间,AMOUNT  AS 交易金额,AUTHORCODE  AS 交易码, FEE  AS 手续费,SYSSERNO AS 系统跟踪号
FROM T_CPS_CUPSICACINFO
WHERE  AUTHORCODE like '32%'
SELECT
    THIRDSYSTIME AS 交易时间,AMOUNT  AS 交易金额,AUTHORCODE  AS 交易码, FEE  AS 手续费,SYSSERNO AS 系统跟踪号
FROM T_CPS_CUPSICACINFO
WHERE  AUTHORCODE like '3_2%';

DB2数据库查询_第3张图片

IN【匹配查询】

SELECT
    THIRDSYSTIME AS 交易时间,AMOUNT  AS 交易金额,AUTHORCODE  AS 交易码, FEE  AS 手续费,SYSSERNO AS 系统跟踪号
FROM T_CPS_CUPSICACINFO
WHERE  FEE in (9.00,4.00)

between...and...【区间查询】要为小写
SELECT
    THIRDSYSTIME AS 交易时间,AMOUNT  AS 交易金额,AUTHORCODE  AS 交易码, FEE  AS 手续费,SYSSERNO AS 系统跟踪号
FROM T_CPS_CUPSICACINFO
WHERE  FEE  between  1.00 and 2.00

DB2数据库查询_第4张图片

4:逻辑筛选

And;or;not

SELECT
    THIRDSYSTIME AS 交易时间,AMOUNT  AS 交易金额,AUTHORCODE  AS 交易码, FEE  AS 手续费,SYSSERNO AS 系统跟踪号
FROM T_CPS_CUPSICACINFO
WHERE  FEE>= 1.00 and FEE<=2.00

DB2数据库查询_第5张图片
or【】
SELECT
    THIRDSYSTIME AS 交易时间,AMOUNT  AS 交易金额,AUTHORCODE  AS 交易码, FEE  AS 手续费,SYSSERNO AS 系统跟踪号
FROM T_CPS_CUPSICACINFO
WHERE  FEE>= 9.00 or FEE<=1.00

DB2数据库查询_第6张图片

5:分组查询  Group by
SELECT
     FEE  AS 手续费,count(FEE) AS 总数,avg(AMOUNT) AS 平均交易金额
FROM T_CPS_CUPSICACINFO
group by FEE

DB2数据库查询_第7张图片
where   group by
SELECT
     FEE  AS 手续费,count(FEE) AS 总数,avg(AMOUNT) AS 平均交易金额
FROM T_CPS_CUPSICACINFO  where FEE>=5.00
group by FEE

DB2数据库查询_第8张图片
where   group by  having
SELECT
     FEE  AS 手续费,count(FEE) AS 总数,avg(AMOUNT) AS 平均交易金额
FROM T_CPS_CUPSICACINFO  where FEE>=5.00
group by FEE having avg(AMOUNT)>500.00

注意:where;group by;having的执行顺序

Where用于筛选有from指定的数据对象;

Group by 用于对wherefrom的结果进行分组

Having是对group by分组数据再进行过滤

With rollup 函数


SELECT
     FEE  AS 手续费,count(FEE) AS 总数,avg(AMOUNT) AS 平均交易金额
FROM T_CPS_CUPSICACINFO
group by FEE  with rollup

DB2数据库查询_第9张图片
6:排序查询

Order by desc【降序】

Order by asc【默认升序】
SELECT
     FEE  AS 手续费,count(FEE) AS 总数,avg(AMOUNT) AS 平均交易金额
FROM T_CPS_CUPSICACINFO where fee>=5.00
group by FEE  order by FEE desc

DB2数据库查询_第10张图片
7: 其他常用聚集函数

Sum【求和】

Avg【平均值】

Max【最大值】

Min【最小值】

Count【行数】
8:子查询

子查询的使用地方相当多,在select,insert,update,delete命令中允许是一个表达式的地方都可以包含子查询

以分页查询为例:

SELECT THIRDSYSTIME AS 交易时间, AMOUNT  AS 交易金额,FEE  AS 手续费,SYSSERNO AS 系统跟踪号
FROM
    (SELECT T_CPS.*,ROWNUMBER() OVER() AS RNUM  FROM
             (SELECT * FROM T_CPS_CUPSICACINFO) AS T_CPS) AS A
WHERE
A.RNUM BETWEEN 10 AND 20; 
DB2数据库查询_第11张图片

你可能感兴趣的:(数据库)