반응형

9.9. Date/Time Functions and Operators

Table 9-28 shows the available functions for date/time value processing, with details appearing in the following subsections. Table 9-27 illustrates the behaviors of the basic arithmetic operators (+*, etc.). For formatting functions, refer to Section 9.8. You should be familiar with the background information on date/time data types from Section 8.5.

All the functions and operators described below that take time or timestamp inputs actually come in two variants: one that takes time with time zone or timestamp with time zone, and one that takes time without time zone or timestamp without time zone. For brevity, these variants are not shown separately. Also, the + and * operators come in commutative pairs (for example both date + integer and integer + date); we show only one of each such pair.

Table 9-27. Date/Time Operators

OperatorExampleResult
+date '2001-09-28' + integer '7'date '2001-10-05'
+date '2001-09-28' + interval '1 hour'timestamp '2001-09-28 01:00:00'
+date '2001-09-28' + time '03:00'timestamp '2001-09-28 03:00:00'
+interval '1 day' + interval '1 hour'interval '1 day 01:00:00'
+timestamp '2001-09-28 01:00' + interval '23 hours'timestamp '2001-09-29 00:00:00'
+time '01:00' + interval '3 hours'time '04:00:00'
-- interval '23 hours'interval '-23:00:00'
-date '2001-10-01' - date '2001-09-28'integer '3' (days)
-date '2001-10-01' - integer '7'date '2001-09-24'
-date '2001-09-28' - interval '1 hour'timestamp '2001-09-27 23:00:00'
-time '05:00' - time '03:00'interval '02:00:00'
-time '05:00' - interval '2 hours'time '03:00:00'
-timestamp '2001-09-28 23:00' - interval '23 hours'timestamp '2001-09-28 00:00:00'
-interval '1 day' - interval '1 hour'interval '1 day -01:00:00'
-timestamp '2001-09-29 03:00' - timestamp '2001-09-27 12:00'interval '1 day 15:00:00'
*900 * interval '1 second'interval '00:15:00'
*21 * interval '1 day'interval '21 days'
*double precision '3.5' * interval '1 hour'interval '03:30:00'
/interval '1 hour' / double precision '1.5'interval '00:40:00'

Table 9-28. Date/Time Functions

FunctionReturn TypeDescriptionExampleResult
age(timestamptimestamp)intervalSubtract arguments, producing a "symbolic" result that uses years and monthsage(timestamp '2001-04-10', timestamp '1957-06-13')43 years 9 mons 27 days
age(timestamp)intervalSubtract from current_date (at midnight)age(timestamp '1957-06-13')43 years 8 mons 3 days
clock_timestamp()timestamp with time zoneCurrent date and time (changes during statement execution); see Section 9.9.4  
current_datedateCurrent date; see Section 9.9.4  
current_timetime with time zoneCurrent time of day; see Section 9.9.4  
current_timestamptimestamp with time zoneCurrent date and time (start of current transaction); see Section 9.9.4  
date_part(texttimestamp)double precisionGet subfield (equivalent to extract); see Section 9.9.1date_part('hour', timestamp '2001-02-16 20:38:40')20
date_part(textinterval)double precisionGet subfield (equivalent to extract); see Section 9.9.1date_part('month', interval '2 years 3 months')3
date_trunc(text,timestamp)timestampTruncate to specified precision; see also Section 9.9.2date_trunc('hour', timestamp '2001-02-16 20:38:40')2001-02-16 20:00:00
extract(field fromtimestamp)double precisionGet subfield; see Section 9.9.1extract(hour from timestamp '2001-02-16 20:38:40')20
extract(field frominterval)double precisionGet subfield; see Section 9.9.1extract(month from interval '2 years 3 months')3
isfinite(date)booleanTest for finite date (not +/-infinity)isfinite(date '2001-02-16')true
isfinite(timestamp)booleanTest for finite time stamp (not +/-infinity)isfinite(timestamp '2001-02-16 21:28:30')true
isfinite(interval)booleanTest for finite intervalisfinite(interval '4 hours')true
justify_days(interval)intervalAdjust interval so 30-day time periods are represented as monthsjustify_days(interval '35 days')1 mon 5 days
justify_hours(interval)intervalAdjust interval so 24-hour time periods are represented as daysjustify_hours(interval '27 hours')1 day 03:00:00
justify_interval(interval)intervalAdjust interval using justify_days and justify_hours, with additional sign adjustmentsjustify_interval(interval '1 mon -1 hour')29 days 23:00:00
localtimetimeCurrent time of day; see Section 9.9.4  
localtimestamptimestampCurrent date and time (start of current transaction); see Section 9.9.4  
now()timestamp with time zoneCurrent date and time (start of current transaction); see Section 9.9.4  
statement_timestamp()timestamp with time zoneCurrent date and time (start of current statement); see Section 9.9.4  
timeofday()textCurrent date and time (like clock_timestamp, but as a text string); see Section 9.9.4  
transaction_timestamp()timestamp with time zoneCurrent date and time (start of current transaction); see Section 9.9.4  

In addition to these functions, the SQL OVERLAPS operator is supported:

(start1, end1) OVERLAPS (start2, end2)
(start1, length1) OVERLAPS (start2, length2)

This expression yields true when two time periods (defined by their endpoints) overlap, false when they do not overlap. The endpoints can be specified as pairs of dates, times, or time stamps; or as a date, time, or time stamp followed by an interval. When a pair of values is provided, either the start or the end can be written first; OVERLAPS automatically takes the earlier value of the pair as the start. Each time period is considered to represent the half-open interval start <= time < end, unless start and end are equal in which case it represents that single time instant. This means for instance that two time periods with only an endpoint in common do not overlap.

SELECT (DATE '2001-02-16', DATE '2001-12-21') OVERLAPS
       (DATE '2001-10-30', DATE '2002-10-30');
Result: true
SELECT (DATE '2001-02-16', INTERVAL '100 days') OVERLAPS
       (DATE '2001-10-30', DATE '2002-10-30');
Result: false
SELECT (DATE '2001-10-29', DATE '2001-10-30') OVERLAPS
       (DATE '2001-10-30', DATE '2001-10-31');
Result: false
SELECT (DATE '2001-10-30', DATE '2001-10-30') OVERLAPS
       (DATE '2001-10-30', DATE '2001-10-31');
Result: true

When adding an interval value to (or subtracting an interval value from) a timestamp with time zone value, the days component advances (or decrements) the date of the timestamp with time zoneby the indicated number of days. Across daylight saving time changes (with the session time zone set to a time zone that recognizes DST), this means interval '1 day' does not necessarily equal interval '24 hours'. For example, with the session time zone set to CST7CDTtimestamp with time zone '2005-04-02 12:00-07' + interval '1 day' will produce timestamp with time zone '2005-04-03 12:00-06', while adding interval '24 hours' to the same initial timestamp with time zone produces timestamp with time zone '2005-04-03 13:00-06', as there is a change in daylight saving time at 2005-04-03 02:00 in time zone CST7CDT.

Note there can be ambiguity in the months returned by age because different months have a different number of days. PostgreSQL's approach uses the month from the earlier of the two dates when calculating partial months. For example, age('2004-06-01', '2004-04-30') uses April to yield 1 mon 1 day, while using May would yield 1 mon 2 days because May has 31 days, while April has only 30.

9.9.1. EXTRACTdate_part

EXTRACT(field FROM source)

The extract function retrieves subfields such as year or hour from date/time values. source must be a value expression of type timestamptime, or interval. (Expressions of type date are cast totimestamp and can therefore be used as well.) field is an identifier or string that selects what field to extract from the source value. The extract function returns values of type double precision. The following are valid field names:

century

The century

SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');
Result: 20
SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 21

The first century starts at 0001-01-01 00:00:00 AD, although they did not know it at the time. This definition applies to all Gregorian calendar countries. There is no century number 0, you go from -1 century to 1 century. If you disagree with this, please write your complaint to: Pope, Cathedral Saint-Peter of Roma, Vatican.

PostgreSQL releases before 8.0 did not follow the conventional numbering of centuries, but just returned the year field divided by 100.

day

For timestamp values, the day (of the month) field (1 - 31) ; for interval values, the number of days

SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 16

SELECT EXTRACT(DAY FROM INTERVAL '40 days 1 minute');
Result: 40
decade

The year field divided by 10

SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 200
dow

The day of the week as Sunday (0) to Saturday (6)

SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 5

Note that extract's day of the week numbering differs from that of the to_char(..., 'D') function.

doy

The day of the year (1 - 365/366)

SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 47
epoch

For date and timestamp values, the number of seconds since 1970-01-01 00:00:00 UTC (can be negative); for interval values, the total number of seconds in the interval

SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');
Result: 982384720.12

SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
Result: 442800

Here is how you can convert an epoch value back to a time stamp:

SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 982384720.12 * INTERVAL '1 second';

(The to_timestamp function encapsulates the above conversion.)

hour

The hour field (0 - 23)

SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 20
isodow

The day of the week as Monday (1) to Sunday (7)

SELECT EXTRACT(ISODOW FROM TIMESTAMP '2001-02-18 20:38:40');
Result: 7

This is identical to dow except for Sunday. This matches the ISO 8601 day of the week numbering.

isoyear

The ISO 8601 week-numbering year that the date falls in (not applicable to intervals)

SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-01');
Result: 2005
SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-02');
Result: 2006

Each ISO 8601 week-numbering year begins with the Monday of the week containing the 4th of January, so in early January or late December the ISO year may be different from the Gregorian year. See the week field for more information.

This field is not available in PostgreSQL releases prior to 8.3.

microseconds

The seconds field, including fractional parts, multiplied by 1 000 000; note that this includes full seconds

SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
Result: 28500000
millennium

The millennium

SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 3

Years in the 1900s are in the second millennium. The third millennium started January 1, 2001.

PostgreSQL releases before 8.0 did not follow the conventional numbering of millennia, but just returned the year field divided by 1000.

milliseconds

The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.

SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
Result: 28500
minute

The minutes field (0 - 59)

SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 38
month

For timestamp values, the number of the month within the year (1 - 12) ; for interval values, the number of months, modulo 12 (0 - 11)

SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 2

SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
Result: 3

SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
Result: 1
quarter

The quarter of the year (1 - 4) that the date is in

SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 1
second

The seconds field, including fractional parts (0 - 59[1])

SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 40

SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
Result: 28.5
timezone

The time zone offset from UTC, measured in seconds. Positive values correspond to time zones east of UTC, negative values to zones west of UTC. (Technically, PostgreSQL uses UT1 because leap seconds are not handled.)

timezone_hour

The hour component of the time zone offset

timezone_minute

The minute component of the time zone offset

week

The number of the ISO 8601 week-numbering week of the year. By definition, ISO weeks start on Mondays and the first week of a year contains January 4 of that year. In other words, the first Thursday of a year is in week 1 of that year.

In the ISO week-numbering system, it is possible for early-January dates to be part of the 52nd or 53rd week of the previous year, and for late-December dates to be part of the first week of the next year. For example, 2005-01-01 is part of the 53rd week of year 2004, and 2006-01-01 is part of the 52nd week of year 2005, while 2012-12-31 is part of the first week of 2013. It's recommended to use the isoyear field together with week to get consistent results.

SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 7
year

The year field. Keep in mind there is no 0 AD, so subtracting BC years from AD years should be done with care.

SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 2001

The extract function is primarily intended for computational processing. For formatting date/time values for display, see Section 9.8.

The date_part function is modeled on the traditional Ingres equivalent to the SQL-standard function extract:

date_part('field', source)

Note that here the field parameter needs to be a string value, not a name. The valid field names for date_part are the same as for extract.

SELECT date_part('day', TIMESTAMP '2001-02-16 20:38:40');
Result: 16

SELECT date_part('hour', INTERVAL '4 hours 3 minutes');
Result: 4

9.9.2. date_trunc

The function date_trunc is conceptually similar to the trunc function for numbers.

date_trunc('field', source)

source is a value expression of type timestamp or interval. (Values of type date and time are cast automatically to timestamp or interval, respectively.) field selects to which precision to truncate the input value. The return value is of type timestamp or interval with all fields that are less significant than the selected one set to zero (or one, for day and month).

Valid values for field are:

microseconds
milliseconds
second
minute
hour
day
week
month
quarter
year
decade
century
millennium

Examples:

SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
Result: 2001-02-16 20:00:00

SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
Result: 2001-01-01 00:00:00

9.9.3. AT TIME ZONE

The AT TIME ZONE construct allows conversions of time stamps to different time zones. Table 9-29 shows its variants.

Table 9-29. AT TIME ZONE Variants

ExpressionReturn TypeDescription
timestamp without time zone AT TIME ZONE zonetimestamp with time zoneTreat given time stamp without time zone as located in the specified time zone
timestamp with time zone AT TIME ZONE zonetimestamp without time zoneConvert given time stamp with time zone to the new time zone, with no time zone designation
time with time zone AT TIME ZONE zonetime with time zoneConvert given time with time zone to the new time zone

In these expressions, the desired time zone zone can be specified either as a text string (e.g., 'PST') or as an interval (e.g., INTERVAL '-08:00'). In the text case, a time zone name can be specified in any of the ways described in Section 8.5.3.

Examples (assuming the local time zone is PST8PDT):

SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'MST';
Result: 2001-02-16 19:38:40-08

SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'MST';
Result: 2001-02-16 18:38:40

The first example takes a time stamp without time zone and interprets it as MST time (UTC-7), which is then converted to PST (UTC-8) for display. The second example takes a time stamp specified in EST (UTC-5) and converts it to local time in MST (UTC-7).

The function timezone(zonetimestamp) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone.

9.9.4. Current Date/Time

PostgreSQL provides a number of functions that return values related to the current date and time. These SQL-standard functions all return values based on the start time of the current transaction:

CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURRENT_TIME(precision)
CURRENT_TIMESTAMP(precision)
LOCALTIME
LOCALTIMESTAMP
LOCALTIME(precision)
LOCALTIMESTAMP(precision)

CURRENT_TIME and CURRENT_TIMESTAMP deliver values with time zone; LOCALTIME and LOCALTIMESTAMP deliver values without time zone.

CURRENT_TIMECURRENT_TIMESTAMPLOCALTIME, and LOCALTIMESTAMP can optionally take a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field. Without a precision parameter, the result is given to the full available precision.

Some examples:

SELECT CURRENT_TIME;
Result: 14:39:53.662522-05

SELECT CURRENT_DATE;
Result: 2001-12-23

SELECT CURRENT_TIMESTAMP;
Result: 2001-12-23 14:39:53.662522-05

SELECT CURRENT_TIMESTAMP(2);
Result: 2001-12-23 14:39:53.66-05

SELECT LOCALTIMESTAMP;
Result: 2001-12-23 14:39:53.662522

Since these functions return the start time of the current transaction, their values do not change during the transaction. This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the "current" time, so that multiple modifications within the same transaction bear the same time stamp.

Note: Other database systems might advance these values more frequently.

PostgreSQL also provides functions that return the start time of the current statement, as well as the actual current time at the instant the function is called. The complete list of non-SQL-standard time functions is:

transaction_timestamp()
statement_timestamp()
clock_timestamp()
timeofday()
now()

transaction_timestamp() is equivalent to CURRENT_TIMESTAMP, but is named to clearly reflect what it returns. statement_timestamp() returns the start time of the current statement (more specifically, the time of receipt of the latest command message from the client). statement_timestamp() and transaction_timestamp() return the same value during the first command of a transaction, but might differ during subsequent commands. clock_timestamp() returns the actual current time, and therefore its value changes even within a single SQL command. timeofday() is a historical PostgreSQL function. Like clock_timestamp(), it returns the actual current time, but as a formatted text string rather than a timestamp with time zone value. now() is a traditional PostgreSQL equivalent to transaction_timestamp().

All the date/time data types also accept the special literal value now to specify the current date and time (again, interpreted as the transaction start time). Thus, the following three all return the same result:

SELECT CURRENT_TIMESTAMP;
SELECT now();
SELECT TIMESTAMP 'now';  -- incorrect for use with DEFAULT

Tip: You do not want to use the third form when specifying a DEFAULT clause while creating a table. The system will convert now to a timestamp as soon as the constant is parsed, so that when the default value is needed, the time of the table creation would be used! The first two forms will not be evaluated until the default value is used, because they are function calls. Thus they will give the desired behavior of defaulting to the time of row insertion.

9.9.5. Delaying Execution

The following function is available to delay execution of the server process:

pg_sleep(seconds)

pg_sleep makes the current session's process sleep until seconds seconds have elapsed. seconds is a value of type double precision, so fractional-second delays can be specified. For example:

SELECT pg_sleep(1.5);


출처 : https://www.postgresql.org/docs/9.1/functions-datetime.html

반응형

'Postgresql' 카테고리의 다른 글

CONNECT BY LEVEL oracle -> postgresql  (0) 2019.01.11
Postgresql 프로시저 만들기  (0) 2019.01.08
Postgresql LPAD() function  (0) 2019.01.08
ORACLE Postgresql 변환  (0) 2018.12.27
Postgresql 스키마 권한  (0) 2018.12.27
반응형

Syntax:

lpad(string,length[,fill_text])

Parameters:

NameDescriptionReturn Type
stringA string, which will be filled up by another string.text
lengthThe length of the string, which will be after filled up by substring..integer
fill_textThe substring which will be fill up the sting to length.text



Pictorial Presentation of PostgreSQL LPAD() function

Pictorial presentation of PostgreSQL LPAD() function




Code:


SELECT lpad('esource', 10, 'w3r');

Sample Output:

    lpad
------------
 w3resource
(1 row)

Example 2:

In the example below, the main string is 'esource' and its length is 7, the substring is 'w3r' of length 3 and the string have to be a length of 13. So, remaining length is 6, and the substring 'w3r' will repeat two times to fill it up, thus the result is 'w3rw3resource'.

Code:

SELECT lpad('esource', 13, 'w3r');

Sample Output:

    lpad
---------------
 w3rw3resource
(1 row)

Example 3:

In the example below, the main string is 'w3resource' and its length is 10, the substring is 'lpad' of length 4 and the string have to be a length of 8. Here, the specified length is smaller than the string, so, instead of lpadding the string will be truncated by two characters from the right side of the string, thus the result is 'w3resour'.

Code:

SELECT lpad('w3resource', 8, 'lpad');

Sample Output:

  lpad
----------
 w3resour
(1 row)



출처 : https://w3resource.com/PostgreSQL/lpad-function.php

반응형

'Postgresql' 카테고리의 다른 글

Postgresql 프로시저 만들기  (0) 2019.01.08
Postgresql 타입별 연산  (0) 2019.01.08
ORACLE Postgresql 변환  (0) 2018.12.27
Postgresql 스키마 권한  (0) 2018.12.27
Postgresql 계층형 쿼리 구현 방법  (0) 2018.12.27
반응형

1. DUAL 
오라클에서 사용하는 DUAL 은 제외하고 사용한다.
SELECT 1 FROM DUAL 과 같이 DUAL 을 사용할 수 없다.
EX> SELECT 1 로만 작성하면 된다.

2. SYSDATE
now() 함수를 사용한다.
EX> SELECT to_char(now(), 'YYYY-MM-DD')

3. NVL
COALESCE 함수를 사용한다
SELECT COALESCE(USER_ID, 0) FROM USER_INFO

4. SEQUENCE(시퀀스)
오라클 시퀀스 문법은 시퀀스명.NEXTVAL 
PostgreSQL 에서는 
NEXTVAL('시퀀스명') 으로 사용한다.

5. ROWNUM
오라클(Oracle)에서 사용하는 ROWNUM 을 PostgreSQL에서 사용하는 방법
    ▶ WHERE 절에서 사용
         SELECT USER_ID FROM USER_INFO LIMIT 3
    ▶ SELECT 절에서 사용
         SELECT (ROW_NUMBER() OVER()) AS ROWNUM , USER_ID FROM USER_INFO
         ==> 
ROW_NUMBER() OVER() 함수를 통하여 ROWNUM을 생성한다.

6. DECODE
PostgreSQL에서는 DECODE 함수를 제공하지 않는다.
CASE문으로 변경한다.

CASE WHEN REG_TYPE = '003' THEN ITEM_TYPE ='QM' ELSE ITEM_TYPE ='GN' END

7. 데이터 형변환
컬럼 혹은 값에 ::[변환할 데이터타입]  붙여서 변환
EX>  SELECT '1'::int

8. Outer Join
▶ 오라클

SELECT D.DNAME, E.EMP_NO FROM DEPT D, EMP E
WHERE  D.DEPT_NO = E.DEPT_NO(+)

▶ PostgreSQL

SELECT D.DNAME, E.EMP_NO 
FROM DEPT D 
LEFT OUTER JOIN EMP E ON D.DEPT_NO = E.DEPT_NO;


출처 : https://m.blog.naver.com/PostView.nhn?blogId=wiseyoun07&logNo=221135110180&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F


반응형

'Postgresql' 카테고리의 다른 글

Postgresql 타입별 연산  (0) 2019.01.08
Postgresql LPAD() function  (0) 2019.01.08
Postgresql 스키마 권한  (0) 2018.12.27
Postgresql 계층형 쿼리 구현 방법  (0) 2018.12.27
Postgresql과 Oracle 차이점  (0) 2018.12.27
반응형

grant all on schema 이름 to postgres;


grant select on all tables in schema 이름 to postgres;

반응형

'Postgresql' 카테고리의 다른 글

Postgresql 타입별 연산  (0) 2019.01.08
Postgresql LPAD() function  (0) 2019.01.08
ORACLE Postgresql 변환  (0) 2018.12.27
Postgresql 계층형 쿼리 구현 방법  (0) 2018.12.27
Postgresql과 Oracle 차이점  (0) 2018.12.27
반응형



▶ 오라클

SELECT 컬럼명
FROM 테이블명
START WITH 계층구조 시작 조건(루트 노드 식별)
CONNECT BY PRIOR 계층구조 상하위 조건(부모 자식 노드간의 관계)

SELECT A.CONTS_ID, 
             A.CONTS_NM,
             A.UP_CONTS_ID,
             A.MENU_ORD,
             LEVEL   /* 계층구조에서 단계레벨을 나타내주는 함수 */
FROM CLT_MENU A
WHERE A.MENU_INCL_YN = 'Y'
             AND LEVEL IN (2,4)
START WITH A.CONTS_ID = 'voc'   /* 계층구조의 시작조건을 주는 조건절 */ 
CONNECT BY PRIOR A.CONTS_ID = A.UP_CONTS_ID  /* 계층구조의 상,하위 간의 관계 조건 */
ORDER SIBLINGS BY A.MENU_ORD   /* 계층구조를 유지하면서 정렬해주는 구문 */

▶ PostgreSQL

WITH RECURSIVE  [view ] (보여주고 싶은 컬럼) as (
    
부모쿼리 작성데이터의 시작조건을 구하는 쿼리
    
lUNION ALL 
    
계층구조 작성, 하위 데이터를 찾아가기 위한 반복 쿼리
)
view 쿼리
 

WITH RECURSIVE CODE_LIST(CONTS_ID, CONTS_NM, UP_CONTS_ID, MENU_ORD, DEPTHPATHCYCLEas (
             /* 계층구조의 시작조건 쿼리 */
             SELECT A.CONTS_ID,
                           A.CONTS_NM,   
                           A.UP_CONTS_ID,
                           A.MENU_ORD,
                           1,
                           ARRAY[A.CONTS_ID::text],
                           false
             
FROM CLT_MENU A
             
WHERE A.CONTS_ID = 'voc'
                           
AND A.MENU_INCL_YN = 'Y'
            
 UNION ALL
             /*하위 데이터를 찾아가기 위한 반복조건 쿼리*/
            
 SELECT A.CONTS_ID,
                           A.CONTS_NM,   
                           A.UP_CONTS_ID,
                           A.MENU_ORD,
                           B.DEPTH + 1,
                           ARRAY_APPEND(B.PATH, A.CONTS_ID::text),
                           A.CONTS_ID = any(B.PATH)
             
FROM CLT_MENU A, CODE_LIST B
             
WHERE A.UP_CONTS_ID = B.CONTS_ID
                           
AND A.MENU_INCL_YN = 'Y'
                           
AND NOT CYCLE
)
/*View 쿼리*/
SELECT CONTS_ID, 
             CONTS_NM, 
             UP_CONTS_ID,
             MENU_ORD, 
             DEPTH AS A_MENU_LEVEL,
             PATH
FROM CODE_LIST
WHERE DEPTH IN (2,4)
ORDER BY PATH 

- CYCLE RECURSIVE를 통한 재귀 쿼리 수행 시 성능 상의 문제를 해결하기 위함
UNION ALL 다음의 반복조건 쿼리가 수행되면 CYCLE false이기 때문에 SELECT문이 수행 되고 검색된 자식 node ID 값이 배열(ARRAY[A.CONTS_ID::text])에 추가(ARRAY_APPEND(B.PATH, A.CONTS_ID::text).
- ANY(B.PATH) PATH 배열에 자신의 ID값이 있는 지를 검사하여이미 찾은 값에 대해서는 더 이상 데이터 검색을 수행하지 않도록 함. 
배열에는 DataType이 int, text인 형태만 담을 수 있으므로 배열에 담을 varchar타입의 컬럼 뒤에 ::text 를 붙여 형태를 변환 해줌.




출처 : https://m.blog.naver.com/wiseyoun07/221135850258





# 오라클(Oracel)


SELECT 컬럼명

FROM 테이블명

START WITH 계층구조 시작 조건(루트 노드 식별)

CONNECT BY PRIOR 계층구조 상하위 조건(부모 자식 노드간의 관계)


 

1
2
3
4
5
6
7
8
SELECT grp_id,
     (LPAD(' ', LEVEL) || grp_nm) as grp_nm,
     top_grp_id,
LEVEL /* 계층구조에서 단계, 레벨을 나타내주는 함수 */
FROM INFO_GROUP 
START WITH top_grp_id IS NULL   /* 계층구조의 시작조건을 주는 조건절 */
CONNECT BY PRIOR grp_id = top_grp_id /* 계층구조의 상,하위 간의 관계 조건 */
ORDER SIBLINGS BY top_grp_id ASC; /* 계층구조를 유지하면서 정렬해주는 구문 */

 





Postgresql


WITH RECURSIVE  [view 명] (보여주고 싶은 컬럼) as (
    부모쿼리 작성, 데이터의 시작조건을 구하는 쿼리
    union all 
    계층구조 작성, 하위 데이터를 찾아가기 위한 반복 쿼리, 
)
view 쿼리


 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
WITH RECURSIVE search_group(grp_id, grp_nm, top_grp_id, level, grp_pathcycle) as (
    /* 계층구조의 시작조건 쿼리 */
    SELECT g.grp_id, 
            g.grp_nm, 
            g.top_grp_id, 
            0
            array[g.grp_id]
            false
    FROM "INFO_GROUP" g
    WHERE g.top_grp_id IS NULL 
    UNION ALL
    /*하위 데이터를 찾아가기위한 반복조건 쿼리*/
    SELECT g.grp_id, 
            g.grp_nm,
            g.top_grp_id, 
            level+1
            grp_path||g.grp_id
            g.grp_id = any(grp_path)
    FROM "INFO_GROUP" g, search_group sg
    WHERE g.top_grp_id = sg.grp_id 
    and NOT cycle
)
/*View 쿼리*/
SELECT grp_id, 
        lpad(' ',level) || grp_nm as grp_nm, 
        top_grp_id, 
        level, 
        grp_path
FROM search_group 
ORDER BY grp_path


cycle은 RECURSIVE를 통한 재귀 쿼리 수행 시 성능 상의 문제를 해결하기 위함


UNION ALL 다음의 반복조건 쿼리가 수행되면 

cycle이 false이기 때문에 SELECT문이 수행이 되고 검색된 자식 node의 ID 값이 배열에 추가(array[g.grp_id])


any(grp_path) 는 grp_path배열에 자신의 ID값이 있는 지를 검사하여, 

이미 찾은 값에 대해서는 더 이상 데이터 검색을 수행하지 않도록 함.





# Postgresql 결과

 

 



출처 : https://m.blog.naver.com/elren/220779694207


반응형

'Postgresql' 카테고리의 다른 글

Postgresql 타입별 연산  (0) 2019.01.08
Postgresql LPAD() function  (0) 2019.01.08
ORACLE Postgresql 변환  (0) 2018.12.27
Postgresql 스키마 권한  (0) 2018.12.27
Postgresql과 Oracle 차이점  (0) 2018.12.27
반응형


--sysdate
oracle : select sysdate from dual;
postgresql : select now();



--dual table
oracle : select 1,2 from dual;
postgresql : select 1,2;



--sequence
oracle : sequence_name.nextval
postgresql : nextval.sequence_name



--decode
oracle : decode(column1, val1, result1, ......, default)
postgresql : case columns1 when val1 then result1 .... else default END



--nvl
oracle : NVL(hire_date, SYSDATE) - 타입 불일치 시 묵시적 형변환 발생
postgresql : coalesce(hire_date, SYSDATE) - 컬럼타입 불일치 시 오류(상수는 OK)



--from절 subquery
oracle : select * from (select * from table_name);
postgresql : select * from (select * from table_name) as alias_name;



--outer join
oracle : select a.field1, b.field2 from a, b where a.item_id = b.item_id(+);
postgresql : select a.field1, b.field2 from a left outer join b on a.item_id = b.item_id;



--connected by
oracle : connected by
postgresql : with recursive



--CLOB
oracle : CLOB
postgresql : TEXT



-- 수치비교
oracle : 문자-숫자 비교시 묵시적 형변환 발생
postgresql : 문자-숫자 비교시 오류 발생

반응형

'Postgresql' 카테고리의 다른 글

Postgresql 타입별 연산  (0) 2019.01.08
Postgresql LPAD() function  (0) 2019.01.08
ORACLE Postgresql 변환  (0) 2018.12.27
Postgresql 스키마 권한  (0) 2018.12.27
Postgresql 계층형 쿼리 구현 방법  (0) 2018.12.27

+ Recent posts