DB2_SQL常用函数

合集下载

db2当前时间函数

db2当前时间函数

db2当前时间函数
在DB2数据库中,可以使用当前时间函数来获取当前的日期和时间。

以下是一些常用的当前时间函数:
1. CURRENT_DATE:返回当前日期,格式为YYYY-MM-DD。

2. CURRENT_TIME:返回当前时间,格式为HH:MM:SS。

3. CURRENT_TIMESTAMP:返回当前日期和时间,格式为
YYYY-MM-DD HH:MM:SS。

可以使用下面的SQL语句来获取当前时间:
SELECT CURRENT_TIMESTAMP FROM SYSIBM.SYSDUMMY1;
输出结果将显示当前的日期和时间。

除了以上的函数,还有一些其他的函数可以用来处理日期和时间。

例如,DATE函数可以从一个日期或时间字符串中提取日期部分,而TIME函数可以从一个日期或时间字符串中提取时间部分。

在使用这些函数时,需要注意数据类型的转换问题。

例如,如果要将一个字符串转换为日期或时间类型,可以使用CAST函数或CONVERT函数来进行转换。

总之,使用当前时间函数可以方便地获取当前的日期和时间,并且在处理日期和时间方面也非常实用。

- 1 -。

db2时间转换函数

db2时间转换函数

db2时间转换函数在DB2中,你可以使用多种函数来转换时间。

以下是一些常用的时间转换函数:1. CAST函数: 用于将一个数据类型转换为另一个数据类型。

```sqlSELECT CAST(column_name AS VARCHAR(10)) FROM table_name; ```2. CONVERT函数: 类似于CAST函数,用于将一个数据类型转换为另一个数据类型。

```sqlSELECT CONVERT(VARCHAR(10), column_name) FROM table_name; ```3. DATE格式化函数: 使用DATE()函数与格式字符串可以格式化日期。

SELECT DATE(column_name, 'YYYY-MM-DD') FROM table_name;```4. TIMESTAMP格式化函数: 使用TIMESTAMP()函数与格式字符串可以格式化日期和时间。

```sqlSELECT TIMESTAMP(column_name, 'YYYY-MM-DD HH:MI:SS') FROM table_name;```5. YEAR(), MONTH(), DAY(): 从日期中提取年份、月份和日期。

```sqlSELECT YEAR(column_name), MONTH(column_name),DAY(column_name) FROM table_name;```6. HOUR(), MINUTE(), SECOND(): 从时间戳中提取小时、分钟和秒。

SELECT HOUR(column_name), MINUTE(column_name),SECOND(column_name) FROM table_name;```7. ADD_MONTHS(): 在日期上添加或减去月份。

```sqlSELECT ADD_MONTHS(column_name, 3) FROM table_name; -- 在日期上加3个月```8. SUBTRACT_MONTHS(): 从日期上减去月份。

db2 判断函数

db2 判断函数

db2 判断函数在DB2中,有许多判断函数可以用于在SQL查询中进行条件判断。

以下是一些常用的判断函数:1. IF函数:IF函数用于根据条件返回不同的值。

其语法如下:```IF (条件, 返回值1, 返回值2)```例如,假设有一个员工表,其中包含工资和部门信息。

你可以使用IF 函数根据部门名称返回不同的工资范围:```sqlSELECT salary,IF(department = 'IT', salary > 5000, salary < 10000) as salary_rangeFROM employees;```2. IIF函数:IIF函数与IF函数类似,但返回的值可以根据多个条件进行判断。

其语法如下:```IIF(条件1, 返回值1, 条件2, 返回值2)```例如,查询员工表中根据部门和职位返回不同的工资范围:```sqlSELECT salary,IIF(department = 'IT' AND position = 'developer', salary * 1.1, IIF(department = 'IT' AND position = 'manager', salary * 1.2,IIF(department = 'finance', salary * 1.3, salary))) as salary_rangeFROM employees;```3. COALESCE函数:COALESCE函数用于返回第一个非空参数。

其语法如下:```COALESCE(参数1, 参数2, 参数3,...)```例如,查询员工表中返回员工的姓名和职位,如果职位为空,则返回“未知职位”:```sqlSELECT name,COALESCE(position, '未知职位') as positionFROM employees;```4. CHECK函数:CHECK函数用于检查表达式是否满足条件,如果满足则返回TRUE,否则返回FALSE。

db2拼接函数范文

db2拼接函数范文

db2拼接函数范文DB2拼接函数是一种在SQL查询中使用的函数,用于将多个字符串值连接在一起。

在DB2中,可以使用以下几种拼接函数:1.CONCAT函数CONCAT函数用于将两个或多个字符串值连接在一起。

语法如下:```CONCAT(string1, string2, ...)```示例:```SELECT CONCAT('Hello', 'World') AS Result FROMSYSIBM.SYSDUMMY1;```结果:HelloWorld2.CONCAT_WS函数CONCAT_WS函数用于将多个字符串值连接在一起,并使用特定分隔符分隔。

语法如下:```CONCAT_WS(separator, string1, string2, ...)```示例:```SELECT CONCAT_WS('-', '2024', '01', '01') AS Result FROM SYSIBM.SYSDUMMY1;```结果:2024-01-013.,运算符运算符也可以用于字符串拼接。

语法如下```string1 , string2 , ...```示例:```SELECT 'Hello' , 'World' AS Result FROM SYSIBM.SYSDUMMY1;```结果:HelloWorld需要注意的是,在DB2中,字符串拼接时要确保操作数的数据类型一致。

如果存在数值类型的操作数,DB2会自动将其转换为字符串类型。

除了上述的单纯拼接函数和运算符外,DB2还提供了其他一些函数来处理字符串拼接的需求:4.VARCHAR_FORMAT函数VARCHAR_FORMAT函数用于将数值类型的数据格式化为字符串。

可以将数值类型与其他字符串拼接。

语法如下:```VARCHAR_FORMAT(value, format)```示例:```SELECT VARCHAR_FORMAT(100, '9999') , ' items' AS Result FROM SYSIBM.SYSDUMMY1;```结果:100 items5.SUBSTR函数SUBSTR函数用于提取指定字符串的子字符串,然后可以与其他字符串进行拼接。

db2sql语法

db2sql语法

db2sql语法===========db2是一种常用的关系型数据库管理系统,它的SQL语法与许多其他SQL数据库系统非常相似,但也具有一些独特的功能和语法特性。

在本文中,我们将介绍db2的基本SQL语法。

一、数据查询------### 1. SELECT语句db2中的SELECT语句用于从数据库中选择数据。

基本的语法如下:```sqlSELECT column_name(s) FROM table_name;```其中,`column_name`是你要选择的列名,`table_name`是你要从中选择数据的表名。

你可以使用多个列名来选择多个列。

如果你想选择所有的列,可以使用星号(*)。

### 2. WHERE子句WHERE子句用于筛选结果集。

它允许你在查询时基于特定条件过滤数据。

基本语法如下:```sqlSELECT column_name(s) FROM table_name WHERE condition;```其中,`condition`是一个逻辑表达式,用于指定你要过滤的条件。

你可以使用各种比较运算符(如=、<、>、<=>等)和逻辑运算符(如AND、OR、NOT等)来构建条件表达式。

### 3. GROUP BY子句GROUP BY子句用于将结果集按照指定的列进行分组。

基本语法如下:```sqlSELECT column_name(s), aggregate_function(column_name(s)) FROM table_name GROUP BY column_name(s);```其中,`aggregate_function`是聚合函数,如SUM、COUNT、AVG 等。

GROUP BY子句允许你按照指定的列对数据进行分组,并使用聚合函数对每个组进行计算。

### 4. HAVING子句HAVING子句用于在GROUP BY查询中过滤分组结果。

它是在GROUP BY子句之后使用的,并且可以对聚合函数的结果进行条件筛选。

DB2函数大全

DB2函数大全

D B2函数大全(共36页)--本页仅作为文档封面,使用时请直接删除即可----内页可以根据需求调整合适字体及大小--第一章聚集函数1.1AVG…………………………………………………………………….平均数1.2CORRELATION……………………………………………………….返回系数1.3COUNT…………………………………………………………………统计函数1.4COVARIANCE…………………………………………………………协方差函数1.5GROUPING…………………………………………………………….分组函数1.6MAX…………………………………………………………………….最大值1.7MIN……………………………………………………………………..最小值1.8Regression……………………………………………………………….回归函数1.9STDDEV…………………………………………………………………偏差函数1.10SUM……………………………………………………………………..求和函数1.11VARIANCE……………………………………………………………..方差函数第二章标量函数2.1ABS……………………………………………………………………….绝对值2.2ASCII……………………………………………………………………..ASCII值2.3BLOB……………………………………………………………………..返回BLOB值2.4CEIL………………………………………………………………………最小整数值2.5CHAR……………………………………………………………………..转换字符串2.6CHR……………………………………………………………………….与ASCII相反2.7CLOB……………………………………………………………………. 返回CLOB值2.8COALESCE………………………………………………………………判断是否为空2.9CONCAT………………………………………………………………….字符串拼接2.10COS……………………………………………………………………….余弦函数2.11COSH……………………………………………………………………...弧度函数2.12COT………………………………………………………………………..余切函数2.13DATE……………………………………………………………………….日期函数2.14DAY…………………………………………………………………………返回天数2.15DAYNAME………………………………………………………………….返回星期2.16DAYOFWEEK……………………………………………………………一周内第N天2.17DAYOFWEEK_ISO………………………………………………………一周内第N天2.18DAYOFYEAR…………………………………………………………….一年内第N天2.19DAYS………………………………………………………………………返回累计天数2.20DBCLOB………………………………………………………………返回DBCLOB值2.21DECIMAL…………………………………………………………返回十进制表示的值2.22DECRYPT_BIN……………………………………………………………数据加密函数2.23DECRYPT_CHAR…………………………………………………………数据加密函数2.24DEGREES……………………………………………………………….. ….返回弧度值2.25DIGITS……………………………………………………………….用字符串表示数值2.26DOUBLE……………………………………………………………..返回双精度浮点型2.27ENCRYPT…………………………………………………………………数据加密函数2.28EVENT_MON_STATE…………………………………………….返回事件监视器状态2.29EXP……………………………………………………………………………..指数函数2.30FLOAT……………………………………………………………. …返回单精度浮点型2.31FLOOR……………………………………………………………………….最大整数值2.32GETHINT………………………………………………………………..取加密后的数据2.33GENERATE_UNIQUE………………………………………………….生成唯一值函数2.34GRAPHIC………………………………………………………………….返回媒体类型2.35HEX………………………………………………………………返回16进制表示的值2.36HOUR………………………………………………………………..返回时间中的小时2.37INSERT……………………………………………………………………查找替换函数2.38LOCATE………………………………………………………………………..查找函数2.39INTEGER………………………………………………………………………取整函数2.40LENGTH…………………………………………………………………….取长度函数2.41LONG_VARCHAR……………………………………………………….返回长字符型2.42LONG_VARGRAPHIC……………………………………………………返回长媒体型2.43LTRIM………………………………………………………………………..去左边空格2.44RTRIM………………………………………………………………………..去右边空格2.45AVG aggregate function>>-AVG--(--+----------+--expression--)-------------------------><'-DISTINCT-'The AVG function returns the average of a set of numbers.Examples:Using the PROJECT table, set the host variable AVERAGE (decimal(5,2)) to the average staffing level (PRSTAFF) of projects in department (DEPTNO) 'D11'.SELECT AVG(PRSTAFF) INTO :AVERAGE FROM PROJECTWHERE DEPTNO = 'D11'Results in AVERAGE being set to (that is 17/4) when using the sample table.Using the PROJECT table, set the host variable ANY_CALC (decimal(5,2)) to the average of each unique staffing level value (PRSTAFF) of projects in department (DEPTNO) 'D11'.SELECT AVG(DISTINCT PRSTAFF)INTO :ANY_CALCFROM PROJECTWHERE DEPTNO = 'D11'Results in ANY_CALC being set to (that is 14/3) when using the sample table.CORRELATION aggregate function>>-+-CORRELATION-+--(--expression1--,--expression2--)----------><'-CORR--------'The CORRELATION function returns the coefficient of correlation of a set of number pairs.The argument values must be numbers.The data type of the result is double-precision floating point. The result can be null. When not null, the result is between -1 and 1.The function is applied to the set of (expression1, expression2) pairs derived from the argument values by the elimination of all pairs for which either expression1 or expression2 is null.If the function is applied to an empty set, or if either STDDEV(expression1) or STDDEV(expression2) is equal to zero, the result is a null value. Otherwise, the resultis the correlation coefficient for the value pairs in the set. The result is equivalent to the following expression:COVARIANCE(expression1,expression2)/(STDDEV(expression1)*STDDEV(expression2))The order in which the values are aggregated is undefined, but every intermediate result must be within the range of the result data type.Example:Using the EMPLOYEE table, set the host variable CORRLN (double-precision floating point) to the correlation between salary and bonus for those employees in department (WORKDEPT) 'A00'.SELECT CORRELATION(SALARY, BONUS)INTO :CORRLNFROM EMPLOYEEWHERE WORKDEPT = 'A00'CORRLN is set to approximately when using the sample table.COUNT aggregate function>>-COUNT--(--+-+----------+--expression-+--)-------------------><| '-DISTINCT-' |'-*------------------------'The COUNT function returns the number of rows or values in a set of rows or values. Examples:Using the EMPLOYEE table, set the host variable FEMALE (int) to the number of rows where the value of the SEX column is 'F'.SELECT COUNT(*) FROM EMPLOYEECOVARIANCE aggregate function>>-+-COVARIANCE-+--(--expression1--,--expression2--)-----------><'-COVAR------'The COVARIANCE function returns the (population) covariance of a set of number pairs.The argument values must be numbers.The data type of the result is double-precision floating point. The result can be null.The function is applied to the set of (expression1,expression2) pairs derived from the argument values by the elimination of all pairs for which either expression1 or expression2 is null.If the function is applied to an empty set, the result is a null value. Otherwise, the result is the covariance of the value pairs in the set. The result is equivalent to the following:Let avgexp1 be the result of AVG(expression1) and let avgexp2 be the result ofAVG(expression2).The result of COVARIANCE(expression1, expression2) is AVG( (expression1 - avgexp1) * (expression2 - avgexp2 )The order in which the values are aggregated is undefined, but every intermediate result must be within the range of the result data type.Example:Using the EMPLOYEE table, set the host variable COVARNCE (double-precision floating point) to the covariance between salary and bonus for those employees in department (WORKDEPT) 'A00'.SELECT COVARIANCE(SALARY, BONUS)INTO :COVARNCEFROM EMPLOYEEWHERE WORKDEPT = 'A00'COVARNCE is set to approximately +006 when using the sample table.GROUPING aggregate function 分组函数>>-GROUPING--(--expression--)----------------------------------><按照SJ分组SELECT grouping(sj) FROM test group by sj则把手机号码相同的分为一组,执行结果为五组1.6 MAX aggregate function 取最大值函数>>-MAX--(--+----------+--expression--)-------------------------><The MAX function returns the maximum value in a set of values. Examples:执行语句:select max(cj) from test结果为:MIN aggregate function 取最小值函数>>-MIN--(--+----------+--expression--)------------------------->< Examples:select min(cj) from test结果为:Regression functions回归函数>>-+-REGR_AVGX----------+--(--expression1--,--expression2--)--->< +-REGR_AVGY----------++-REGR_COUNT---------++-+-REGR_INTERCEPT-+-+| '-REGR_ICPT------' |+-REGR_R2------------++-REGR_SLOPE---------++-REGR_SXX-----------++-REGR_SXY-----------+'-REGR_SYY-----------'The regression functions support the fitting of an ordinary-least-squares regression line of the form y = a * x + b to a set of number pairs. The first element of each pair (expression1) is interpreted as a value of the dependent variable (that is, a "y value"). The second element of each pair (expression2 ) is interpreted as a value of the independent variable (that is, an "x value").The REGR_COUNT function returns the number of non-null number pairs used to fit the regression line (see below).The REGR_INTERCEPT (or REGR_ICPT) function returns the y-intercept of the regression line ("b" in the above equation).The REGR_R2 function returns the coefficient of determination ("R-squared" or "goodness-of-fit") for the regression.The REGR_SLOPE function returns the slope of the line ("a" in the above equation).The REGR_AVGX, REGR_AVGY, REGR_SXX, REGR_SXY, and REGR_SYY functions return quantities that can be used to compute various diagnostic statistics needed for the evaluation of the quality and statistical validity of the regression model (see below).The argument values must be numbers.The data type of the result of REGR_COUNT is integer. For the remaining functions, the data type of the result is double precision floating point. The result can be null. When not null, the result of REGR_R2 is between 0 and 1, and the result of both REGR_SXX and REGR_SYY is non-negative.Each function is applied to the set of (expression1, expression2) pairs derived from the argument values by the elimination of all pairs for which either expression1 or expression2 is null.If the set is not empty and VARIANCE(expression2) is positive, REGR_COUNT returns the number of non-null pairs in the set, and the remaining functions return results that are defined as follows:REGR_SLOPE(expression1,expression2) =COVARIANCE(expression1,expression2)/VARIANCE(expression2)REGR_INTERCEPT(expression1, expression2) =AVG(expression1) - REGR_SLOPE(expression1, expression2) * AVG(expression2) REGR_R2(expression1, expression2) =POWER(CORRELATION(expression1, expression2), 2) if VARIANCE(expression1)>0 REGR_R2(expression1, expression2) = 1 if VARIANCE(expression1)=0REGR_AVGX(expression1, expression2) = AVG(expression2)REGR_AVGY(expression1, expression2) = AVG(expression1)REGR_SXX(expression1, expression2) =REGR_COUNT(expression1, expression2) * VARIANCE(expression2)REGR_SYY(expression1, expression2) =REGR_COUNT(expression1, expression2) * VARIANCE(expression1)REGR_SXY(expression1, expression2) =REGR_COUNT(expression1, expression2) * COVARIANCE(expression1, expression2) If the set is not empty and VARIANCE(expression2) is equal to zero, then the regression line either has infinite slope or is undefined. In this case, the functions REGR_SLOPE, REGR_INTERCEPT, and REGR_R2 each return a null value, and the remaining functions return values as defined above. If the set is empty,REGR_COUNT returns zero and the remaining functions return a null value.The order in which the values are aggregated is undefined, but every intermediate result must be within the range of the result data type.The regression functions are all computed simultaneously during a single pass through the data. In general, it is more efficient to use the regression functions to compute the statistics needed for a regression analysis than to perform the equivalent computations using ordinary column functions such as AVERAGE, VARIANCE, COVARIANCE, and so forth.The usual diagnostic statistics that accompany a linear-regression analysis can be computed in terms of the above functions. For example:Adjusted R21 - ( (1 - REGR_R2) * ((REGR_COUNT - 1) / (REGR_COUNT - 2)) )Standard errorSQRT( (REGR_SYY-(POWER(REGR_SXY,2)/REGR_SXX))/(REGR_COUNT-2) )Total sum of squaresREGR_SYYRegression sum of squaresPOWER(REGR_SXY,2) / REGR_SXXResidual sum of squares(Total sum of squares)-(Regression sum of squares)t statistic for slopeREGR_SLOPE * SQRT(REGR_SXX) / (Standard error)t statistic for y-interceptREGR_INTERCEPT/((Standard error) *SQRT((1/REGR_COUNT)+(POWER(REGR_AVGX,2)/REGR_SXX))Example:Using the EMPLOYEE table, compute an ordinary-least-squares regression line that expresses the bonus of an employee in department (WORKDEPT) 'A00' as a linear function of the employee's salary. Set the host variables SLOPE, ICPT, RSQR (double-precision floating point) to the slope, intercept, and coefficient of determination of the regression line, respectively. Also set the host variables AVGSAL and AVGBONUS to the average salary and average bonus, respectively, of the employees in department 'A00', and set the host variable CNT (integer) to the number of employees in department 'A00' for whom both salary and bonus data are available. Store the remaining regression statistics in host variables SXX, SYY, and SXY. SELECT REGR_SLOPE(BONUS,SALARY), REGR_INTERCEPT(BONUS,SALARY),REGR_R2(BONUS,SALARY), REGR_COUNT(BONUS,SALARY),REGR_AVGX(BONUS,SALARY), REGR_AVGY(BONUS,SALARY),REGR_SXX(BONUS,SALARY), REGR_SYY(BONUS,SALARY),REGR_SXY(BONUS,SALARY)INTO :SLOPE, :ICPT,:RSQR, :CNT,:AVGSAL, :AVGBONUS,:SXX, :SYY,:SXYFROM EMPLOYEEWHERE WORKDEPT = 'A00'When using the sample table, the host variables are set to the following approximate values:SLOPE: +ICPT: ++002RSQR: +CNT: 3AVGSAL: ++004AVGBONUS: ++002SXX: ++008SYY: ++004SXY: ++006STDDEV aggregate function 求平均差值函数>>-STDDEV--(--+----------+--expression--)----------------------><The STDDEV function returns the standard deviation of a set of numbers.The argument values must be numbers.The data type of the result is double-precision floating point. The result can be null. Example: 使用(样表二)SELECT STDDEV(cj) FROM TEST结果为:===================================================================== ============================================1.10 SUM aggregate function 求和函数>>-SUM--(--+----------+--expression--)-------------------------><The SUM function returns the sum of a set of numbers.Example: 使用(样表二)SELECT SUM(cj) FROM TEST结果为:============================================1.11 VARIANCE aggregate function方差函数>>-+-VARIANCE-+--(--+----------+--expression--)----------------><The VARIANCE function returns the variance of a set of numbers.The argument values must be numbers.Example:Using the EMPLOYEE table, set the host variable VARNCE (double-precision floating point) to the variance of the salaries for those employees in department (WORKDEPT) 'A00'.SELECT VARIANCE(SALARY)INTO :VARNCEFROM EMPLOYEEWHERE WORKDEPT = 'A00'结果为: .88.第二章标量函数2.1 ABS or ABSVAL scalar function 求绝对值>>-+-ABS----+--(--expression--)--------------------------------><'-ABSVAL-'Example:ABS(-51234)结果为:51234.===================================================================== ================================2.2 ASCII scalar function 求ASCII>>-ASCII--(--expression--)-------------------------------------><返回整数参数最左边的字符的ASCII码select ascii(name) from test where id='ddd'结果为:972.3 BLOB scalar function>>-BLOB--(--string-expression--+------------+--)---------------><The BLOB function returns a BLOB representation of a string of any type.string-expressionA string-expression whose value can be a character string, graphic string, or a binary string.integerAn integer value specifying the length attribute of the resulting BLOB data type. If integer is not specified, the length attribute of the result is the same as the length of the input, except where the input is graphic. In this case, the length attribute of the result is twice the length of the input.The result of the function is a BLOB. If the argument can be null, the result can be null; if the argument is null, the result is the null value.ExamplesGiven a table with a BLOB column named TOPOGRAPHIC_MAP and a VARCHAR column named MAP_NAME, locate any maps that contain the string 'Pellow Island' and return a single binary string with the map name concatenated in front of the actual map.SELECT BLOB(MAP_NAME || ': ') || TOPOGRAPHIC_MAPFROM ONTARIO_SERIES_4WHERE TOPOGRAPHIC_MAP LIKE BLOB('%Pellow Island%')2.4 CEILING or CEIL scalar function>>-+-CEILING-+--(--expression--)-------------------------------><'-CEIL----'返回比参数大或等于参数的最小的整数值Examples:使用(样表二)select name,cj,ceil(cj)from test2.5 CHAR scalar functionCharacter to Character:>>-CHAR--(--character-expression--+------------+--)------------><'-,--integer-'Datetime to Character:>>-CHAR--(--datetime-expression--+--------------+--)-----------><'-,--+-ISO---+-'+-USA---++-EUR---++-JIS---+'-LOCAL-'Integer to Character:>>-CHAR--(--integer-expression--)------------------------------><Decimal to Character:>>-CHAR--(--decimal-expression--+----------------------+--)----><'-,--decimal-character-'Floating-point to Character:>>-CHAR--(--floating-point-expression--------------------------->>--+----------------------+--)---------------------------------><'-,--decimal-character-'The CHAR function returns a fixed-length character string representation of:注意:The CAST expression can also be used to return a string expression.The result of the function is a fixed-length character string. If the first argument can be null, the result can be null. If the first argument is null, the result is the null value. Examples: 使用(样表一)select char(rq,usa) from test where id='ddd'结果为:10/01/2006select char(rq,iso) from test where id='ddd'结果为:2006-10-01例子2:Assume that the PRSTDATE column has an internal value equivalent to 1988-12-25. The following function returns the value '12/25/1988'.CHAR(PRSTDATE, USA)Assume that the STARTING column has an internal value equivalent to 17:12:30, and that the host variable HOUR_DUR (decimal(6,0)) is a time duration with a value of 050000 (that is, 5 hours). The following function returns the value '5:12 PM'.CHAR(STARTING, USA)The following function returns the value '10:12 PM'.CHAR(STARTING + :HOUR_DUR, USA)Assume that the RECEIVED column (TIMESTAMP) has an internal value equivalent to the combination of the PRSTDATE and STARTING columns. The following function returns the value '.'.CHAR(RECEIVED)The LASTNAME column is defined as VARCHAR(15). The following function returns the values in this column as fixed-length character strings that are 10 characters long. LASTNAME values that are more than 10 characters long (excluding trailing blanks) are truncated and a warning is returned.SELECT CHAR(LASTNAME,10) FROM EMPLOYEEThe EDLEVEL column is defined as SMALLINT. The following function returns the values in this column as fixed-length character strings. An EDLEVEL value of 18 is returned as the CHAR(6) value '18 ' ('18' followed by four blanks).SELECT CHAR(EDLEVEL) FROM EMPLOYEEThe SALARY column is defined as DECIMAL with a precision of 9 and a scale of 2. The current value is to be displayed with a comma as the decimal character (18357,50). The following function returns the value '00018357,50'.CHAR(SALARY, ',')Values in the SALARY column are to be subtracted from and displayed with the default decimal character. The following function returns the value ''.CHAR - SALARY)Assume that the host variable SEASONS_TICKETS is defined as INTEGER and has a value of 10000. The following function returns the value ' '.CHAR(DECIMAL(:SEASONS_TICKETS,7,2))Assume that the host variable DOUBLE_NUM is defined as DOUBLE and has a value of . The following function returns the value ' '. Because the result data type is CHAR(24), there are nine trailing blanks in the result.CHAR(:DOUBLE_NUM)===================================================================== ====================================================================CHR scalar function>>-CHR--(--expression--)---------------------------------------><根据ASCII值返回字符例子:select chr(65) from结果为:A2.7 CLOB scalar function>>-CLOB--(--character-string-expression--+------------+--)-----><'-,--integer-'The CLOB function returns a CLOB representation of a character string type. In a Unicode database, if a supplied argument is a graphic string, it is first converted to a character string before the function is executed.character-string-expressionAn expression that returns a value that is a character string.integerAn integer value specifying the length attribute of the resulting CLOB data type. The value must be between 0 and 2 147 483 647. If integer is not specified, the length of the result is the same as the length of the first argument.The result of the function is a CLOB. If the argument can be null, the result can be null; if the argument is null, the result is the null value.2.8 COALESCE scalar function>>-COALESCE-------(--expression----,--expression-+--)----------><判断字段是否为空,如果为空侧返回一个值Examples: 使用(样表一)ID=’111’的记录BZ字段为空select COALESCE(bz,'显示的值') from test where id='111'结果为:显示的值2.9 CONCAT scalar function>>-CONCAT-------(--expression1--,--expression2--)--------------><注意:|| may be used as a synonym for CONCAT.The schema is SYSIBM.返回2个值串相连,但是这2个值类型必须相同.例子:select id,concat(name,'测试') from test where id='001'结果为:刘飞测试2.10 COS scalar function>>-COS--(--expression--)---------------------------------------><The schema is SYSIBM. (The SYSFUN version of the COS function continues to be available.)Returns the cosine of the argument, where the argument is an angle expressed in radians.The argument can be of any built-in numeric type. It is converted to a double-precision floating-point number for processing by the function.The result of the function is a double-precision floating-point number. The result can be null if the argument can be null or the database is configured withDFT_SQLMATHWARN set to YES; the result is the null value if the argument is null.2.11 COSH scalar function弧度函数>>-COSH--(--expression--)--------------------------------------><The schema is SYSIBM.Returns the hyperbolic cosine of the argument, where the argument is an angle expressed in radians.The argument can be of any built-in numeric data type. It is converted to a double-precision floating-point number for processing by the function.The result of the function is a double-precision floating-point number. The result can be null if the argument can be null or the database is configured withDFT_SQLMATHWARN set to YES; the result is the null value if the argument is null.2.12 COT scalar function余切函数>>-COT--(--expression--)---------------------------------------><The schema is SYSIBM. (The SYSFUN version of the COT function continues to be available.)Returns the cotangent of the argument, where the argument is an angle expressedin radians.The argument can be of any built-in numeric type. It is converted to a double-precision floating-point number for processing by the function.The result of the function is a double-precision floating-point number. The result can be null if the argument can be null or the database is configured withDFT_SQLMATHWARN set to YES; the result is the null value if the argument is null.2.13 DATE scalar function日期函数>>-DATE--(--expression--)--------------------------------------><返回一个日期格式的值The argument must be a date, timestamp, a positive number less than or equal to 3 652 059, a valid string representation of a date or timestamp, or a string of length 7 that is not a CLOB, LONG VARCHAR, DBCLOB, or LONG VARGRAPHIC.The result of the function is a date. If the argument can be null, the result can be null; if the argument is null, the result is the null value.The other rules depend on the data type of the argument:If the argument is a date, timestamp, or valid string representation of a date or timestamp:The result is the date part of the value.If the argument is a number:The result is the date that is n-1 days after January 1, 0001, where n is the integral part of the number.If the argument is a string with a length of 7:The result is the date represented by the string.Examples:Assume that the column RECEIVED (timestamp) has an internal value equivalent to '.'. This example results in an internal representation of '1988-12-25'.DATE(RECEIVED)This example results in an internal representation of '1988-12-25'.DATE('1988-12-25')This example results in an internal representation of '1988-12-25'.DATE('')This example results in an internal representation of '0001-02-04'.DATE(35)2.14 DAY scalar function日期函数>>-DAY--(--expression--)---------------------------------------><The DAY function returns the day part of a value.The argument must be a date, timestamp, date duration, timestamp duration, or a valid character string representation of a date or timestamp that is neither a CLOB nor a LONG VARCHAR. In a Unicode database, if a supplied argument is a graphic string, it is first converted to a character string before the function is executed. The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.Examples:使用表TEST,日期2006-10-2select day(‘2006-10-2’)结果为:22.15 DAYNAME scalar function 返回星期>>-DAYNAME--(--expression--)-----------------------------------><返回一个日期中的天数,是一周中的星期几例子:Select dayname(‘2006-10-10’) from test结果为:星期二2.16 DAYOFWEEK scalar function>>-DAYOFWEEK--(--expression--)---------------------------------><返回该天是一周中的第几天,星期天作为一周的第一天===================================================================== ============================================================== 2.17 DAYOFWEEK_ISO scalar function>>-DAYOFWEEK_ISO--(--expression--)-----------------------------><返回该天是一周中的第几天,星期天作为一周的第一天2.18 DAYOFYEAR scalar function>>-DAYOFYEAR--(--expression--)---------------------------------><返回该天是一年中的第几天===================================================================== ================================2.19 DAYS scalar function>>-DAYS--(--expression--)--------------------------------------><返回一个天数The DAYS function returns an integer representation of a date.The argument must be a date, timestamp, or a valid character string representation of a date or timestamp that is neither a CLOB nor a LONG VARCHAR. In a Unicode database, if a supplied argument is a graphic string, it is first converted to a character string before the function is executed.The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.The result is 1 more than the number of days from January 1, 0001 to D, where D is the date that would occur if the DATE function were applied to the argument.===================================================================== ====================================================2.20 DBCLOB scalar function>>-DBCLOB--(--graphic-expression--+------------+--)------------><'-,--integer-'返回一个DBCLOB型的类型值2.21 DECIMAL()。

db2数据库 sql常用命令

db2数据库 sql常用命令

DB2数据库 SQL常用命令一、连接数据库1. 从命令行连接数据库- 语法: db2 connect to <database_name> user <username> using <password>- 示例: db2 connect to sample user db2inst1 using passw0rd2. 从命令行断开数据库连接- 语法: db2 connect reset- 示例: db2 connect reset3. 显示当前连接的数据库- 语法: db2 list database directory- 示例: db2 list database directory二、管理数据库对象4. 创建数据库- 语法: db2 create database <database_name>- 示例: db2 create database sample5. 删除数据库- 语法: db2 drop database <database_name>- 示例: db2 drop database sample6. 创建表- 语法: db2 create table <table_name> (<column1_name> <data_type>, <column2_name> <data_type>, ...)- 示例: db2 create table employee (id int, name varchar(50), age int)7. 删除表- 语法: db2 drop table <table_name>- 示例: db2 drop table employee8. 插入数据- 语法: db2 insert into <table_name> values (<value1>,<value2>, ...)- 示例: db2 insert into employee values (1, 'John', 25)9. 删除数据- 语法: db2 delete from <table_name> where <condition> - 示例: db2 delete from employee where id = 110. 更新数据- 语法: db2 update <table_name> set <column_name> =<new_value> where <condition>- 示例: db2 update employee set age = 30 where id = 111. 查询数据- 语法: db2 select <column1_name>, <column2_name>, ... from <table_name> where <condition>- 示例: db2 select * from employee三、管理数据库事务12. 启动事务- 语法: db2 autmit off- 示例: db2 autmit off13. 提交事务- 语法: db2mit- 示例: db2mit14. 回滚事务- 语法: db2 rollback- 示例: db2 rollback四、管理数据库权限15. 创建用户- 语法: db2 create user <username> password <password> - 示例: db2 create user testuser password testpass16. 授权- 语法: db2 grant <privilege> on <object> to <user>- 示例: db2 grant select, insert, update on employee to testuser17. 撤销授权- 语法: db2 revoke <privilege> on <object> from <user> - 示例: db2 revoke select, insert, update on employee from testuser五、管理数据库性能18. 优化SQL查询- 语法: db2expln -d <database_name> -t <sql_statement> - 示例: db2expln -d sample -t "select * from employee"19. 查看数据库锁- 语法: db2 list applications show det本人l- 示例: db2 list applications show det本人l20. 查看数据库表空间使用情况- 语法: db2pd -d <database_name> -tablespaces- 示例: db2pd -d sample -tablespaces六、其他常用命令21. 导出数据- 语法: db2 export to <file_name> of del select * from<table_name>- 示例: db2 export to employee.csv of del select * from employee22. 导入数据- 语法: db2 import from <file_name> of del insert into<table_name>- 示例: db2 import from employee.csv of del insert into employee23. 查看数据库配置参数- 语法: db2 get db cfg for <database_name>- 示例: db2 get db cfg for sample结语以上就是DB2数据库SQL常用命令的介绍,通过掌握这些命令,可以更方便地管理和使用DB2数据库。

db2数据库sql技巧

db2数据库sql技巧

db2数据库sql技巧
1.使用FLOAT和REAL数据类型来存储浮点数:
在DB2中,如果需要存储浮点数,最好使用FLOAT或REAL数据类型,这两种数据类型可以保存较大的精度,可以将有效位数从15位延伸到31位,可以保存极大的数值范围。

2.使用独立的子查询而不是JOIN子句:
可以使用独立的子查询而不是JOIN子句,它们可以更有效地反映查
询的意图,并且更易于维护。

它们还能对SQL查询的执行速度带来很大的
改善。

3.使用COUNT(函数:
COUNT( 函数可以找出数据表中的其中一字段的总计数,它可以很容
易的结合 Group by 子句来计算查询的结果。

4.使用UNIONALL代替UNION:
使用UNIONALL来合并相关表的查询结果,这样可以减少一步排除重
复记录的操作,从而提高查询的执行效率。

5.使用DISTINCT关键字:
使用DISTINCT关键字可以清除相关表的重复记录,从而减少查询的
结果集,从而提高查询的效率。

6.使用LIKE关键字:
使用LIKE关键字可以模糊查询,可以定位出匹配的字符串,同时还
可以使用通配符(%和_)来缩小范围。

7.使用DECLARE 语句:
使用DECLARE语句可以定义变量和数据类型,它们可以在SQL查询中使用,可以提高编程的效率,减少重复编程的时间。

8.使用WITH查询:。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

DB2函数大全函数名函数解释函数举例AVG() 返回一组数值的平均值.SELECTAVG(SALARY)FROMBSEMPMS;CORR(),CORRELATION() 返回一对数值的关系系数.SELECT CORRELATION(SALARY,BONUS)FROM BSEMPMS; COUNT() 返回一组行或值的个数.SELECTCOUNT(*)FROMBSEMPMS;COVAR(),COVARIANCE() 返回一对数值的协方差.SELECTCOVAR(SALARY,BONUS)FROMBSEMPMS; MAX() 返回一组数值中的最大值.SELECTMAX(SALARY)FROMBSEMPMS;MIN() 返回一组数值中的最小值.SELECTMIN(SALARY)FROMBSEMPMS;STDDEV() 返回一组数值的标准偏差.SELECTSTDDEV(SALARY)FROMBSEMPMS;SUM() 返回一组数据的和.SELECTSUM(SALARY)FROMBSEMPMS;VAR(),VARIANCE() 返回一组数值的方差.SELECTVARIANCE(SALARY)FROMBSEMPMS;ABS(),ABSVAL() 返回参数的绝对值.SELECTABS(-3.4)FROMBSEMPMS;ACOS() 返回参数的反余弦值.SELECTACOS(0.9)FROMBSEMPMS;ASCII() 返回整数参数最左边的字符的ASCII码.SELECTASCII('R')FROMBSEMPMS;ASIN() 返回用弧度表示的角度的参数的反正弦函数.SELECTASIN(0.9)FROMBSEMPMS;ATAN() 返回参数的反正切值,该参数用弧度表示的角度的参数.SELECTATAN(0.9)FROMBSEMPMS;ATAN2() 返回用弧度表示的角度的X和Y坐标的反正切值.SELECTATAN2(0.5,0.9)FROMBSEMPMS;BIGINT() 返回整型常量中的数字或字符串的64位整数表示SELECTBIGINT(EMP_NO)FROMBSEMPMS;CEILING() OR CEIL() 返回比参数大或等于参数的最小的整数值CHAR() 返回日期时间型,字符串,整数,十进制或双精度浮点数的字符串表示. SELECTCHAR(SALARY,',')FROMBSEMPMS; CHR() 返回具有由参数指定的ASCII码的字符SELECTCHAR(167)FROMBSEMPMS;CONCAT() 返回两个字符串的连接.SELECTCONCAT(EMP_NO,EMP_NAM)FROMBSEMPMS; YEAR() 返回数值的年部分.SELECTYEAR('2003/01/02')FROMBSEMPMS; VARCHAR() 返回字符串,日期型,图形串的可变长度的字符串表示SELECTVARCHAR(EMP_NAM,50)FROMBSEMPMS; UCASE() OR UPPER() 返回字符串的大写TRUNCATE() OR TRUNC() 从表达式小数点右边的位置开始截断并返回该数值.SELECTTRUNCATE(345.6789,2)FROMBSEMPMS;TIME() 返回一个数值中的时间SELECTTIME('2001-03-19.12.30.123456')FROMBSEMPMS; SUBSTR(EXP1,EXP2) 返回EXP1串自EXP2处开始的子串.SQRT() 返回该参数的平方根.SELECTSQRT(36)FROMBSEMPMS;SPACE() 返回由参数指定的长度,包含空格在内的字符串.SELECTSPACE(10)FROMBSEMPMS;SECOND() 返回一个数值的秒部分.SELECTSECOND('18:34:32')FROMBSEMPMS; RTRIM() 删除字符串尾部的空格.SELECTRTRIM('COMMENT')FROMBSEMPMS; ROUND(EXP1,EXP2) 返回EXP1小数点右边的第EXP2位置处开始的四舍五入值.SELECTROUND(2345.6789,2)FROMBSEMPMS REPLACE(EXP1,EXP2,EXP3用EXP3替代EXP1中所有的EXP2)SELECTCHAR(REPLACE('ROMANDD','NDD','CCB'),10)FROMBSEMPMS;REPEAT(EXP1,EXP2) 返回EXP1重复EXP2次后的字符串.SELECTCHAR(REPEAT('REPEAT',3),21)FROMBSEMPMS; REAL() 返回一个数值的单精度浮点数表示.SELECTREAL(10)FROMBSEMPMS;RAND() 返回0和1之间的随机浮点数.SELECTRAND()FROMBSEMPMS;POWER(EXP1,EXP2) 返回EXP1的EXP2次幂.SELECTPOWER(2,5)FROMBSEMPMS;POSSTR(EXP1,EXP2) 返回EXP2在EXP1中的位置.SELECT('ABCDEFGH','D')FROMBSEMPMS; NULLIF(EXP1,EXP2) 如果EXP1=EXP2,则为NULL,否则为EXP1 NODENUMBER() 返回行的分区号.SELECTNODENUMBER(EMP_NO)FROMBSEMPMS;MONTH() 返回一个数值的月部分.SELECTMONTH('2003/10/20')FROMBSEMPMS; MOD(EXP1,EXP2) 返回EXP1除以EXP2的余数.SELECTMOD(20,8)FROMBSEMPMSMINUTE() 返回一个数值的分钟部分.SELECTMINUTE('18:34:23')FROMBSEMPMS; LTRIM() 删除字符串前面的空格.SELECTLTRIM('CDDD')FROMBSEMPMS;HOUR() 返回一个数值的小时部分.SELECTHOUR('18:34:23')FROMBSEMPMS; DOUBLE() 如果参数是一个数字表达式,返回与其相对应的浮点数,如果参数是字符串表达式,则返回该数的字符串表达式.SELECTDOUBLE('5678')FROMBSEMPMS;EXP() 返回参数的指数函数.SELECTEXP(2)FROMBSEMPMS; FLOAT() 返回一个数的浮点表示.SELECTFLOAT(789)FROMBSEMPMS;FLOOR() 返回小于或等于参数的最大整数.SLECTFLOOR(88.93)FROMBSEMPMS;HEX() 返回一个表示为字符串的值的16进制表示.SELECTHEX(16)FROMBSEMPMS;DAYNAME 返回一个大小写混合的字符串,对于参数的日部分,用星期表示这一天的名称(例如,Friday)。

DAYOFWEEK 返回参数中的星期几,用范围在 1-7 的整数值表示,其中 1 代表星期日。

DAYOFWEEK_ISO 返回参数中的星期几,用范围在 1-7 的整数值表示,其中 1 代表星期一。

DAYOFYEAR 返回参数中一年中的第几天,用范围在 1-366 的整数值表示。

DAYS 返回日期的整数表示。

JULIAN_DAY 返回从公元前 4712 年 1 月 1 日(儒略日历的开始日期)到参数中指定日期值之间的天数,用整数值表示。

MIDNIGHT_SECONDS 返回午夜和参数中指定的时间值之间的秒数,用范围在 0 到 86400 之间的整数值表示。

MONTHNAME 对于参数的月部分的月份,返回一个大小写混合的字符串(例如,January)。

TIMESTAMP_ISO 根据日期、时间或时间戳记参数而返回一个时间戳记值。

TIMESTAMP_FORMAT 从已使用字符模板解释的字符串返回时间戳记。

TIMESTAMPDIFF 根据两个时间戳记之间的时差,返回由第一个参数定义的类型表示的估计时差。

TO_CHAR 返回已用字符模板进行格式化的时间戳记的字符表示。

TO_CHAR 是 VARCHAR_FORMAT 的同义词。

TO_DATE 从已使用字符模板解释过的字符串返回时间戳记。

TO_DATE 是 TIMESTAMP_FORMAT 的同义词。

WEEK 返回参数中一年的第几周,用范围在 1-54 的整数值表示。

以星期日作为一周的开始。

WEEK_ISO 返回参数中一年的第几周,用范围在 1-53 的整数值表示。

要使当前时间或当前时间戳记调整到 GMT/CUT,则把当前的时间或时间戳记减去当前时区寄存器:current time - current timezonecurrent timestamp - current timezone给定了日期、时间或时间戳记,则使用适当的函数可以单独抽取出(如果适用的话)年、月、日、时、分、秒及微秒各部分:YEAR (current timestamp)MONTH (current timestamp)DAY (current timestamp)HOUR (current timestamp)MINUTE (current timestamp)SECOND (current timestamp)MICROSECOND (current timestamp)因为没有更好的术语,所以您还可以使用英语来执行日期和时间计算:current date + 1 YEARcurrent date + 3 YEARS + 2 MONTHS + 15 DAYScurrent time + 5 HOURS - 3 MINUTES + 10 SECONDS从时间戳记单独抽取出日期和时间也非常简单:DATE (current timestamp)TIME (current timestamp)而以下示例描述了如何获得微秒部分归零的当前时间戳记:CURRENT TIMESTAMP - MICROSECOND (current timestamp) MICROSECONDS如果想将日期或时间值与其它文本相衔接,那么需要先将该值转换成字符串。

为此,只要使用 CHAR() 函数:char(current date)char(current time)char(current date + 12 hours)要将字符串转换成日期或时间值,可以使用:TIMESTAMP ('2002-10-20-12.00.00.000000')TIMESTAMP ('2002-10-20 12:00:00')DATE ('2002-10-20')DATE ('10/20/2002')TIME ('12:00:00')TIME ('12.00.00')TIMESTAMP()、DATE() 和 TIME() 函数接受更多种格式。

相关文档
最新文档