55
1 SQL problēmas 1. Problēma. Vienas rindas salīdzināšana ar citām rindām. SELECT FROM T1 a WHERE nevar norādīt 2 rindas a SELECT FROM T1 a b WHERE a.KOL1 > b.KOL1 SELECT FROM T1 b WHERE

Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

Embed Size (px)

Citation preview

Page 1: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

1

SQL problēmas

1. Problēma. Vienas rindas salīdzināšana ar citām rindām.

SELECT FROM T1 a WHERE nevar norādīt 2 rindas

a

SELECTFROM T1 a b WHERE a.KOL1 > b.KOL1

SELECTFROM T1 bWHERE

Page 2: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

2

2. Problēma. Kā vienlaicīgi iegūt vērtību no tabulas rindas un agregētu vērtību no vairākām tabulas rindām?

Tabula DARBINIEKINODALAS_NUMURS

UZVARDS ALGA

1 Koks 2001 Zars 3502 Sakne 3002 Ozols 2502 Liepa 350

Vaicājuma rezultātsUZVARDS ALGA Kopeja_algaKoks 200 550Zars 350 550Sakne 300 900Ozols 250 900Liepa 350 900

Page 3: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

3

Analīzes funkcijas (analytic functions) 1. Analīzes funkcijas aprēķina kopējo vērtību, pamatojoties uz rakstu grupu.

2. Tās atšķiras no agregātu funkcijām, jo atgriež vairākas rindas katrai grupai. Rindu grupu sauc par logu, un tā ir definēta ar analīzes klauzulu. Katrai rindai tiek definēts "slīdošs"rindu logs. Logs nosaka rindu diapazonu, kas tiek izmantots, lai veiktu aprēķinus “pašreizējai rindai”. Logu lielumi var balstīties uz fizisku rindu skaitu vai loģisku intervālu, piemēram, laiku.

3. Analīzes funkcijas ir pēdējais vaicājumā veikto operāciju kopums, izņemot klauzulu ORDER BY. Visi savienojumi un visi WHERE, GROUP BY un HAVING klauzulas tiek pabeigtas, pirms tiek apstrādātas analīzes funkcijas. Tāpēc analīzes funkcijas var parādīties tikai izvēles sarakstā vai klauzulā ORDER BY. Analīzes funkcijas parasti tiek izmantotas, lai aprēķinātu kumulatīvo, pārvietojamo, centrēto un pārskatu apkopojumu.

analytic_function::=

Specify the name of an analytic function. Analytic functions take 0 to 3 arguments. The arguments can be any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type. Oracle determines the argument with the highest numeric precedence and implicitly converts the remaining arguments to that data type. The return type is also that data type, unless otherwise noted for an individual function. Use OVER analytic_clause to indicate that the function operates on a query result set. This clause is computed after the FROM, WHERE, GROUP BY, and HAVING clauses. You can specify analytic functions with this clause in the select list or ORDER BY clause. To filter the results of a query based on an analytic function, nest these functions within the parent query, and then filter the results of the nested subquery. You cannot nest analytic functions by specifying any analytic function in any part of the analytic_clause. However, you can specify an analytic function in a subquery and compute another analytic function over it.You can specify OVER analytic_clause with user-defined analytic functions as well as built-in analytic functions.

Page 4: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

4

analytic_clause::=

query_partition_clause::=

Use the PARTITION BY clause to partition the query result set into groups based on one or more value_expr. If you omit this clause, then the function treats all rows of the query result set as a single group.

To use the query_partition_clause in an analytic function, use the upper branch of the syntax (without parentheses). To use this clause in a model query (in the model_column_clauses) or a partitioned outer join (in the outer_join_clause), use the lower branch of the syntax (with parentheses).You can specify multiple analytic functions in the same query, each with the same or different PARTITION BY keys.If the objects being queried have the parallel attribute, and if you specify an analytic function with the query_partition_clause, then the function computations are parallelized as well.Valid values of value_expr are constants, columns, nonanalytic functions, function expressions, or expressions involving any of these.

Page 5: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

5

order_by_clause::=

Use the order_by_clause to specify how data is ordered within a partition. For all analytic functions you can order the values in a partition on multiple keys, each defined by a value_expr and each qualified by an ordering sequence.Within each function, you can specify multiple ordering expressions. Doing so is especially useful when using functions that rank values, because the second expression can resolve ties between identical values for the first expression.Whenever the order_by_clause results in identical values for multiple rows, the function behaves as follows:

1) CUME_DIST, DENSE_RANK, NTILE, PERCENT_RANK, and RANK return the same result for each of the rows;

2) ROW_NUMBER assigns each row a distinct value even if there is a tie based on the order_by_clause. The value is based on the order in which the row is processed, which may be nondeterministic if the ORDER BY does not guarantee a total ordering.

3) for all other analytic functions, the result depends on the window specification. If you specify a logical window with the RANGE keyword, then the function returns the same result for each of the rows. If you specify a physical window with the ROWS keyword, then the result is nondeterministic.

Restrictions on the ORDER BY Clause The following restrictions apply to the ORDER BY clause:

1) when used in an analytic function, the order_by_clause must take an expression (expr). The SIBLINGS keyword is not valid (it is relevant only in hierarchical queries). Position (position) and column aliases (c_alias) are also invalid. Otherwise this order_by_clause is the same as that used to order the overall query or subquery.

2) an analytic function that uses the RANGE keyword can use multiple sort keys in its ORDER BY clause if it specifies any of the following windows:

- RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. The short form of this is RANGE UNBOUNDED PRECEDING.

- RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING- RANGE BETWEEN CURRENT ROW AND CURRENT ROW

Page 6: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

6

- RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING

Window boundaries other than these four can have only one sort key in the ORDER BY clause of the analytic function. This restriction does not apply to window boundaries specified by the ROW keyword.ASC | DESC Specify the ordering sequence (ascending or descending). ASC is the default.NULLS FIRST | NULLS LAST Specify whether returned rows containing nulls should appear first or last in the ordering sequence.NULLS LAST is the default for ascending order, and NULLS FIRST is the default for descending order.Analytic functions always operate on rows in the order specified in the order_by_clause of the function. However, the order_by_clause of the function does not guarantee the order of the result. Use the order_by_clause of the query to guarantee the final result ordering.

Page 7: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

7

Analītisko funkciju pamatkoncepcijas

1. Apstrādes kārtība. Vaicājuma apstrāde, izmantojot analīzes funkcijas, notiek trijos posmos:1) tiek veikti visi savienojumi, WHERE, GROUP BY un HAVING klauzulas;2) rezultātu kopa ir pieejama analīzes funkcijām, un visi to aprēķini notiek;3) ja vaicājuma beigās ir klauzula ORDER BY, tiek apstrādāts ORDER BY, lai realizētu precīzu izvades kārtību.

2. Rezultātu kopas partīcijas. Analīzes funkcijas ļauj lietotājiem sadalīt vaicājuma rezultātu kopas rindu grupās, ko sauc par nodalījumiem. Ievērojiet, ka ar analīzes funkcijām izmantotie terminu nodalījumi nav saistīti ar tabulas nodalījumiem. Visā šajā nodaļā terminu nodalījumi attiecas tikai uz nozīmi, kas saistīta ar analīzes funkcijām. Nodalījumi tiek izveidoti pēc grupām, kas definētas ar klauzulām GROUP BY, tāpēc tās ir pieejamas visiem apkopotajiem rezultātiem, piemēram, summām un vidējiem rādītājiem. Nodalījumu sadalīšanas pamatā var būt nepieciešamās kolonnas vai izteiksmes. Vaicājuma rezultātu kopa var tikt sadalīta vienā nodalījumā, kurā ir visas rindas, daži lieli nodalījumi vai daudzi mazi nodalījumi, kas satur tikai dažas rindas.

3. Logs (window). Katrai nodalījuma rindai var definēt slīdošo datu logu. Šis logs nosaka rindu diapazonu, kas tiek izmantots pašreizējās rindas aprēķinu veikšanai. Logu lielumi var balstīties uz fizisku rindu skaitu vai loģisku intervālu, piemēram, laiku. Logam ir sākuma rinda un beigu rinda. Atkarībā no tā definīcijas logs var pārvietoties vienā vai abos galos. Piemēram, logam, kas definēts kumulatīvai summai, būtu sākuma rinda, kas fiksēta tā nodalījuma pirmajā rindā, un tā beigu rinda no sākuma punkt punkta aizslīdētu līdz pēdējai nodalījuma rindai. Savukārt logam, kas definēts kustīgai vidējai vērtībai, būtu gan tā sākuma, gan beigu punkti, lai tie saglabātu konstantu fizisko vai loģisko diapazonu. Logu var iestatīt tik lielu kā visas nodalījuma rindas vai vienas rindas slīdošais logs nodalījumā. Ja logs atrodas pie apmales, funkcija atgriež tikai pieejamās rindas, nevis brīdina, ka rezultāti nav tas, ko vēlaties.

4. Pašreizējā rinda. Katra analīzes funkcija veiktā aprēķina pamatā ir pašreizējā rinda nodalījumā. Pašreizējā rinda kalpo kā atskaites punkts, kas nosaka loga sākumu un beigas.

Page 8: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

8

Slīdošā loga (sliding window) piemērs

windowing_clause ::=

Page 9: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

9

Some analytic functions allow the windowing_clause. In the listing of analytic functions at the end of this section, the functions that allow the windowing_clause are followed by an asterisk (*).ROWS | RANGE These keywords define for each row a window (a physical or logical set of rows) used for calculating the function result. The function is then applied to all the rows in the window. The window moves through the query result set or partition from top to bottom.

1) ROWS specifies the window in physical units (rows). 2) RANGE specifies the window as a logical offset.

You cannot specify this clause unless you have specified the order_by_clause. Some window boundaries defined by the RANGE clause let you specify only one expression in the order_by_clause. The value returned by an analytic function with a logical offset is always deterministic. However, the value returned by an analytic function with a physical offset may produce nondeterministic results unless the ordering expression results in a unique ordering. You may have to specify multiple columns in the order_by_clause to achieve this unique ordering.BETWEEN ... AND Use the BETWEEN ... AND clause to specify a start point and end point for the window. The first expression (before AND) defines the start point and the second expression (after AND) defines the end point.If you omit BETWEEN and specify only one end point, then Oracle considers it the start point, and the end point defaults to the current row.UNBOUNDED PRECEDING Specify UNBOUNDED PRECEDING to indicate that the window starts at the first row of the partition. This is the start point specification and cannot be used as an end point specification.UNBOUNDED FOLLOWING Specify UNBOUNDED FOLLOWING to indicate that the window ends at the last row of the partition. This is the end point specification and cannot be used as a start point specification.CURRENT ROW As a start point, CURRENT ROW specifies that the window begins at the current row or value (depending on whether you have specified ROW or RANGE, respectively). In this case the end point cannot be value_expr PRECEDING.As an end point, CURRENT ROW specifies that the window ends at the current row or value (depending on whether you have specified ROW or RANGE, respectively). In this case the start point cannot be value_expr FOLLOWING.value_expr PRECEDING or value_expr FOLLOWING For RANGE or ROW:

1) if value_expr FOLLOWING is the start point, then the end point must be value_expr FOLLOWING.

2) If value_expr PRECEDING is the end point, then the start point must be value_expr PRECEDING.

If you are defining a logical window defined by an interval of time in numeric format, then you may need to use conversion functions.

Page 10: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

10

If you specified ROWS:1) value_expr is a physical offset. It must be a constant or expression and must evaluate to a positive numeric value.2) if value_expr is part of the start point, then it must evaluate to a row before the end point.If you specified RANGE:

1) value_expr is a logical offset. It must be a constant or expression that evaluates to a positive numeric value or an interval literal. You can specify only one expression in the order_by_clause.

2) if value_expr evaluates to a numeric value, then the ORDER BY expr must be a numeric or DATE data type.

3) if value_expr evaluates to an interval value, then the ORDER BY expr must be a DATE data type.

If you omit the windowing_clause entirely, then the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.Analytic functions are commonly used in data warehousing environments. In the list of analytic functions that follows, functions followed by an asterisk (*) allow the full syntax, including the windowing_clause.

Page 11: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

11

Klona tabulas izmantošana

1. Izmantojot OVER() konstrukciju vaicājuma SELECT daļā, tiek veidots tabulas klons jeb kopija.

2. Katrai pamattabulas rindai tiek veidots slīdošs rindu logs klona tabulā. Loga rindas tiek izmantotas, lai veiktu aprēķinus par pašreizējo rindu.

3. Rindu apjomu logā var noteikt kā skaitli (skaits) vai loģisku vērtību (laika periods).

4. Analītiskās funkcijas aprēķina kopvērtību jeb agregāta vērtību, izmantojot klona tabulas datu rakstu (rindu) grupu.

5. Rindu grupu sauc par logu un tas tiek definēts ar analītisko teikumu (analytic_clause).

6. Analītiskās funkcijas parasti izmanto, lai aprēķinātu kumulatīvas, dināmiskas, centrētas un citas atskaišu vērtības.

Page 12: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

12

SQL papildinājumi datu analīzei

1. Kārtošanas (ranking), klona tabulas (windowing) un pārskatu

funkcijas.

2. Uzlabotās agregātfunkcijas datu analīzei.

3. Šķērstabulu (pivoting) darbības.

4. Datu sablīvēšana pārskatu veidošanai.

5. Laika sēriju aprēķini sablīvētiem datiem.

6. Dažādu analīžu (miscellaneous analysis) iespējas.

Page 13: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

13

Funkcijas, kas tiek izmantotas analītiskajās funkcijās

Type Used forRanking  Calculating ranks, percentiles, and n-tiles of the values in a

result set. Windowing  Calculating cumulative and moving aggregates. Works with

these functions: SUM, AVG, MIN, MAX, COUNT, VARIANCE, STDDEV, FIRST_VALUE, LAST_VALUE, and new statistical functions 

Reporting  Calculating shares (akcijas), for example, market share. Works with these functions: SUM, AVG, MIN, MAX, COUNT (with/without DISTINCT), VARIANCE, STDDEV, RATIO_TO_REPORT, and new statistical functions 

LAG/LEAD  Finding a value in a row a specified number of rows from a current row. 

FIRST/LAST  First or last value in an ordered group. Linear Regression  Calculating linear regression and other statistics (slope,

intercept, and so on). Inverse Percentile  The value in a data set that corresponds to a specified

percentile. Hypothetical Rank and Distribution 

The rank or percentile that a row would have if inserted into a specified data set. 

Page 14: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

14

Analītiskās funkcijasCOUNT*COVAR_POP*COVAR_SAMP*CUME_DISTDENSE_RANKFIRSTFIRST_VALUE*LAGLASTLAST_VALUE*LEADLISTAGGMAX*MEDIANMIN*NTH_VALUE*NTILEPERCENT_RANKPERCENTILE_CONTPERCENTILE_DISCRANKRATIO_TO_REPORTREGR_ (Linear Regression) Functions*ROW_NUMBERSTDDEV*STDDEV_POP*STDDEV_SAMP*SUM*VAR_POP*VAR_SAMP*VARIANCE*

Page 15: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

15

Laika sērijas aprēķini attiecībā uz sablīvētiem datiem

Densifikācija nav tikai ziņošanas nolūkam. Tas ļauj arī noteikt konkrētus aprēķinu veidus, jo īpaši laika sēriju aprēķinus. Laika sērijas aprēķini ir vieglāki, ja dati ir blīvi laika dimensijā. Blīviem datiem ir konsekvents rindu skaits katram laika periodam, kas savukārt ļauj vienkārši izmantot analīzes loga funkcijas ar fiziskām nobīdēm.

Periodu salīdzinājums vienam laika līmenim

Kā izmantot šo līdzekli, lai salīdzinātu vērtības laika periodos? Konkrēti, kā aprēķināt gada pārdošanas salīdzinājumu nedēļas līmenī? Šajā pašā rindā tiek atgriezts šāds vaicājums katram produktam – gada pārdošana par katru 2001. gada nedēļu ar 2000. gada nedēļu.

Vairāku laika līmeņu periodu salīdzinājums

Lai gan iepriekšējais piemērs rāda veidu, kā izveidot salīdzinājumus vienā laika līmenī, būtu vēl lietderīgāk apstrādāt vairākus laika līmeņus vienā vaicājumā. Piemēram, var salīdzināt pārdošanas apjomus salīdzinājumā ar iepriekšējo periodu gadā, ceturksnī, mēnesī un dienas līmenī. Kā izveidot vaicājumu, kas veic gada salīdzinājumu par gada pārdošanu visos mūsu laika hierarhijas līmeņos?

Page 16: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

16

Klona tabulas (windowing) izmantošanas piemēri

create table DARBINIEKI(D_NUM number Primary Key,UZV varchar2(10),NODALA number,AMATS varchar2(15),ALGA number(10,2));begininsert into DARBINIEKI values(1001, 'Koks', 1, 'direktors', 500);insert into DARBINIEKI values(1002, 'Celms', 2, 'direktors', 550);insert into DARBINIEKI values(1003, 'Sakne', 3, 'direktors', 400);insert into DARBINIEKI values(1004, 'Lapa', 1, 'sekretāre', 300);insert into DARBINIEKI values(1005, 'Oga', 2, 'sekretāre', 250);insert into DARBINIEKI values(1006, 'Zars', 3, 'sekretāre', 150);insert into DARBINIEKI values(1007, 'Irbe', 1, 'galdnieks', 400);insert into DARBINIEKI values(1008, 'Cauna', 2, 'skārdnieks', 500);insert into DARBINIEKI values(1009, 'Sesks', 3, 'krāsotājs', 450);end;select * from DARBINIEKI;

Page 17: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

17

Aktuāls vaicājums: Kā vienlaicīgi iegūt vērtību no tabulas rindas un agregētu vērtību no vairākām tabulas rindām?

select NODALA, UZV, ALGA, SUM(ALGA) OVER(order by NODALA) Kopeja_algafrom DARBINIEKI;

select NODALA, UZV, ALGA, SUM(ALGA) OVER (partition by NODALA) KOPEJA_ALGAfrom DARBINIEKI;

Page 18: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

18

select NODALA, ALGA, ALGA*100/SUM(ALGA) OVER (partition by NODALA) ALGAS_PROCENTSfrom DARBINIEKI;

select NODALA, ALGA, FLOOR(ALGA*100/SUM(ALGA) OVER (partition by NODALA)) ALGAS_PROCENTSfrom DARBINIEKI;

Page 19: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

19

select UZV, NODALA, ALGA, RANK() OVER (partition by NODALA order by ALGA) ALGAS_RANGSfrom DARBINIEKI;

UZV NODALA ALGA ALGAS_RANGS----------------------------------------------------------------------------Lapa 1 300 1Irbe 1 300 1 Vienādās vērtībasKoks 1 500 3Oga 2 250 1Cauna 2 500 2Celms 2 550 3Zars 3 150 1Sakne 3 400 2Sesks 3 450 3

Page 20: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

20

select UZV, NODALA, ALGA, DENSE_RANK() OVER (PARTITION BY NODALA ORDER BY ALGA) ALGAS_RANGSfrom DARBINIEKI;

UZV NODALA ALGA ALGAS_RANGS--------------------------------------------------------------------Lapa 1 300 1Irbe 1 300 1 Vienādās vērtībasKoks 1 500 2Oga 2 250 1Cauna 2 500 2Celms 2 550 3Zars 3 150 1Sakne 3 400 2Sesks 3 450 3

select UZV, NODALA, ALGA, SUM(ALGA) OVER (PARTITION BY NODALA ORDER BY ALGA RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) asALGU_SUMMAfrom DARBINIEKI;

UZV NODALA ALGA ALGU_SUMMA----------------------------------------------------------------------Lapa 1 300 300Irbe 1 400 700Koks 1 500 1200Oga 2 250 250Cauna 2 500 750Celms 2 550 1300Zars 3 150 150Sakne 3 400 550Sesks 3 450 1000

Page 21: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

21

select UZV, NODALA, ALGA, MAX(ALGA) OVER (PARTITION BY NODALA ORDER BY ALGA DESC ROWS 1 PRECEDING) AS ALGA_MAXfrom DARBINIEKI;

UZV NODALA ALGA ALGA_MAX----------------------------------------------------------------------Koks 1 500 500Irbe 1 400 500Lapa 1 300 400Celms 2 550 550Cauna 2 500 550Oga 2 250 500Sesks 3 450 450Sakne 3 400 450Zars 3 150 400

Page 22: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

22

Laiks un analītiskās funkcijas

create table DARBINIEKI(NUM number Primary key,UZV varchar2(10) NOT NULL,DAT_NO date,DAT_LIDZ date ,DARBS varchar2(15),ALGA number(8,2),VAD number,DEP number);

alter session set NLS_DATE_FORMAT = 'DD-MM-RRRR' ;

insert into DARBINIEKI values(1, 'Koks', '07-05-2000', '18-08-2008', 'projekti', 1500, NULL, 1 );insert into DARBINIEKI values(2, 'Stumbrs', '10-07-2000', '21-09-2007', 'projekts1', 1200, 1, 1 );insert into DARBINIEKI values(3, 'Sakne', '10-07-2000', '02-02-2009', 'projekts2', 1200, 1, 2 );insert into DARBINIEKI values(4, 'Lapa', '21-03-2001', '30-04-2008', 'projekts1', 1000, 2, 1 );insert into DARBINIEKI values(5, 'Zars', '22-04-2002', '25-11-2008', 'projekts1', 900, 2, 1 );insert into DARBINIEKI values(6, 'Priede', '15-11-2001', '05-05-2005', 'projekts2', 1100, 3, 2 );insert into DARBINIEKI values(7, 'Egle', '17-10-2002', '12-12-2008', 'projekts2', 800, 3, 2 ); 

select * from DARBINIEKI;

Page 23: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

23

LAG funkcija (iepriekējais vai iepriekš-iepriekšējais)It provides access to more than one row of a table at the same time without a self join. Given a series of rows returned from a query and a position of the cursor, LAG provides access to a row at a given physical offset prior to that position.For the optional offset argument, specify an integer that is greater than zero. If you do not specify offset, then its default is 1. The optional default value is returned if the offset goes beyond the scope of the window. If you do not specify default, then its default is null.{RESPECT | IGNORE} NULLS determines whether null values of value_expr are included in or eliminated from the calculation. The default is RESPECT NULLS.You cannot nest analytic functions by using LAG or any other analytic function for value_expr. However, you can use other built-in function expressions for value_expr.

select DAT_NO, UZV, ALGA, LAG(ALGA, 1, 50 ) OVER (ORDER BY DAT_NO) as iepriekš_alga from DARBINIEKI where DARBS = 'projekts1'

Page 24: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

24

LEAD funkcija (uz priekšu)It provides access to more than one row of a table at the same time without a self join. Given a series of rows returned from a query and a position of the cursor, LEAD provides access to a row at a given physical offset beyond that position.If you do not specify offset, then its default is 1. The optional default value is returned if the offset goes beyond the scope of the table. If you do not specify default, then its default value is null.{RESPECT | IGNORE} NULLS determines whether null values of value_expr are included in or eliminated from the calculation. The default is RESPECT NULLS.You cannot nest analytic functions by using LEAD or any other analytic function for value_expr. However, you can use other built-in function expressions for value_expr.

select DAT_NO, UZV, ALGA, LEAD(ALGA, 1, 50 ) OVER (ORDER BY DAT_NO) as UZ_priekšu_algafrom DARBINIEKIwhere DARBS = 'projekts1';

Page 25: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

25

LISTAGG funkcijaFor a specified measure, LISTAGG orders data within each group specified in the ORDER BY clause and then concatenates the values of the measure column.1. As a single-set aggregate function, LISTAGG operates on all rows and returns a single output row.2. As a group-set aggregate, the function operates on and returns an output row for each group defined by the GROUP BY clause.3. As an analytic function, LISTAGG partitions the query result set into groups based on one or more expression in the query_partition_clause.The arguments to the function are subject to the following rules:

1) the measure_expr can be any expression. Null values in the measure column are ignored.2) the delimiter_expr designates the string that is to separate the measure values. This clause is

optional and defaults to NULL.3) the order_by_clause determines the order in which the concatenated values are returned.

The function is deterministic only if the ORDER BY column list achieved unique ordering.The return data type is RAW if the measure column is RAW; otherwise the return value is VARCHAR2.

select LISTAGG(UZV, '; ') WITHIN GROUP (ORDER BY DAT_NO, UZV) "Saraksts", MIN(DAT_NO) "Agrākais" from DARBINIEKI where DEP =1;

select DEP as "Departaments", LISTAGG(UZV, '; ') WITHIN GROUP (ORDER BY DAT_NO) "Darbinieki"from DARBINIEKIgroup by DEP order by DEP;

Page 26: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

26

select DEP as "Departaments", DAT_NO "Datums", UZV "Uzvārds", LISTAGG(UZV, '; ') WITHIN GROUP (ORDER BY DAT_NO, UZV) OVER(PARTITION BY DEP) as "Darbin_saraksts"

from DARBINIEKI where DAT_NO < TO_DATE('01-07-2001', 'DD-MM-YYYY') order by DEP, DAT_NO, UZV;

Page 27: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

27

RATIO_TO_REPORT funkcijaRATIO_TO_REPORT is an analytic function. It computes the ratio of a value to the sum of a set of values. If expr evaluates to null, then the ratio-to-report value also evaluates to null.The set of values is determined by the query_partition_clause. If you omit that clause, then the ratio-to-report is computed over all rows returned by the query.You cannot nest analytic functions by using RATIO_TO_REPORT or any other analytic function for expr. However, you can use other built-in function expressions for expr.

select UZV, ALGA, RATIO_TO_REPORT(ALGA) OVER() as Attiecfrom DARBINIEKIWHERE DARBS = 'projekts1'order by UZV, ALGA, Attiec; // Sakārtošana jādara ārpus OVER()

Page 28: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

28

NTILE funkcija

NTILE is an analytic function. It divides an ordered data set into a number of buckets indicated by expr and assigns the appropriate bucket number to each row. The buckets are numbered 1 through expr. The expr value must resolve to a positive constant for each partition. Oracle Database expects an integer, and if expr is a noninteger constant, then Oracle truncates the value to an integer. The return value is NUMBER.The number of rows in the buckets can differ by at most 1. The remainder values (the remainder of number of rows divided by buckets) are distributed one for each bucket, starting with bucket 1.If expr is greater than the number of rows, then a number of buckets equal to the number of rows will be filled, and the remaining buckets will be empty.You cannot nest analytic functions by using NTILE or any other analytic function for expr. However, you can use other built-in function expressions for expr.

select UZV, ALGA, NTILE(3) OVER (ORDER BY ALGA DESC) Dalījumsfrom DARBINIEKIwhere DEP = 1order by UZV, ALGA, Dalījums;

Page 29: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

29

NTH_VALUE funkcijaNTH_VALUE returns the measure_expr value of the nth row in the window defined by the analytic_clause. The returned value has the data type of the measure_expr.

1) {RESPECT | IGNORE} NULLS determines whether null values of measure_expr are included in or eliminated from the calculation. The default is RESPECT NULLS.

2) n determines the nth row for which the measure value is to be returned. n can be a constant, bind variable, column, or an expression involving them, as long as it resolves to a positive integer. The function returns NULL if the data source window has fewer than n rows. If n is null, then the function returns an error.

3) FROM {FIRST | LAST} determines whether the calculation begins at the first or last row of the window. The default is FROM FIRST.

If you omit the windowing_clause of the analytic_clause, it defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. This default sometimes returns an unexpected value for NTH_VALUE ... FROM LAST ... , because the last value in the window is at the bottom of the window, which is not fixed. It keeps changing as the current row changes. For expected results, specify the windowing_clause as RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. Alternatively, you can specify the windowing_clause as RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING.

The following example shows the minimum amount_sold value for the second channel_id in ascending order for each prod_id between 13 and 16:

SELECT prod_id, channel_id, MIN(amount_sold), NTH_VALUE(MIN(amount_sold), 2) OVER (PARTITION BY prod_id ORDER BY channel_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) nv FROM sales WHERE prod_id BETWEEN 13 and 16 GROUP BY prod_id, channel_id;

PROD_ID CHANNEL_ID MIN(AMOUNT_SOLD) NV------------------------------------------------------------------------------------------ 13 2 907.34 906.2 13 3 906.2 906.2 13 4 842.21 906.2 14 2 1015.94 1036.72 14 3 1036.72 1036.72 14 4 935.79 1036.72 15 2 871.19 871.19 15 3 871.19 871.19

15 4 871.19 871.19

Page 30: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

30

16 2 266.84 266.84 16 3 266.84 266.84 16 4 266.84 266.84 16 9 11.99 266.84

Page 31: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

31

Piemēri klona tabulas izmantošanai laika datu gadījumāselect * from ALGA_T;

UZV NODALA ALGA DATUMS------------------------------------------------------------Koks 1 150 2000.01.10Koks 1 160 2000.02.10Koks 1 170 2000.03.10Koks 1 180 2000.04.10Koks 1 190 2000.05.10Koks 1 200 2000.06.10Celms 2 150 2000.02.10Celms 2 160 2000.03.10Celms 2 160 2000.04.10Celms 2 170 2000.05.10Celms 2 190 2000.06.10Celms 2 200 2000.07.10

SELECT UZV, ALGA, SUM(ALGA) OVER (ORDER BY ALGA ROWS 1 PRECEDING) as PLUS_ALGA_IEPRIEKŠĒJĀ from ALGA_Twhere NODALA =1;

UZV ALGA PLUS_ALGA_IEPRIEKŠĒJĀ-----------------------------------------------------------Koks 150 150Koks 160 310Koks 170 330Koks 180 350Koks 190 370Koks 200 390

Page 32: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

32

select UZV, ALGA, SUM(ALGA) OVER (ORDER BY DATUMS RANGE BETWEEN CURRENT ROW AND INTERVAL '1' MONTH FOLLOWING) as PLUS_MĒNESIS_UZ_PRIEKŠUfrom ALGA_Twhere NODALA =1;

UZV ALGA PLUS_MĒNESIS_UZ_PRIEKŠU-----------------------------------------------------------------------------Koks 150 310Koks 160 330Koks 170 350Koks 180 370Koks 190 390Koks 200 200

select UZV, ALGA, LAST_VALUE(ALGA) OVER (ORDER BY ALGA ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS NĀKOŠĀfrom ALGA_Twhere NODALA =1;

UZV ALGA NĀKOŠĀ--------------------------------------------Koks 150 160Koks 160 170Koks 170 180Koks 180 190Koks 190 200Koks 200 200

Page 33: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

33

select UZV, ALGA, ALGA - LAST_VALUE(ALGA) OVER (ORDER BY ALGA ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS NĀKOŠĀfrom ALGA_Twhere NODALA =1;

UZV ALGA NĀKOŠĀ------------------------------------------------Koks 150 -10Koks 160 -10Koks 170 -10Koks 180 -10Koks 190 -10Koks 200 0

select A.UZV, A.ALGA, ABS(A.STARPĪBA)from (select UZV, ALGA, ALGA - LAST_VALUE(ALGA) OVER (ORDER BY ALGA ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) as STARPĪBA from ALGA_T where NODALA =1) A ;

UZV ALGA ABS(A.NAKOSA)--------------------------------------------------------Koks 150 10Koks 160 10Koks 170 10Koks 180 10Koks 190 10Koks 200 0

Page 34: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

34

select A.UZV, MAX(ABS(A.STARPĪBA))from (select UZV, ALGA, ALGA - LAST_VALUE(ALGA) OVER (ORDER BY ALGA ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) as STARPĪBA from ALGA_T where NODALA =1) Agroup by A.UZV;

UZV MAX(ABS(A.STARPĪBA))------------------------------------------------Koks 10

select CASE WHEN ABS(A.NAKOSA) <5 THEN 'Zem 5' WHEN ABS(A.NAKOSA) >= 5 THEN 'Virs 5' END, COUNT(ABS(A.NAKOSA))from (select UZV, ALGA, ALGA - LAST_VALUE(ALGA) OVER (ORDER BY ALGA ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS NAKOSA from ALGA_T where NODALA =1) A group by CASE WHEN ABS(A.NAKOSA) <5 THEN 'Zem 5' WHEN ABS(A.NAKOSA) >= 5 THEN 'Virs 5' END;

CASE WH COUNT(ABS(A.NAKOSA))-----------------------------------------------------------------Virs 5 5Zem 5 1

Page 35: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

35

Piemēri klona tabulas izmantošanai laika datu gadījumā

create table D_ALGA (ID number Primary Key,UZV varchar2(10),DZIMUMS char(8),VIENIBA number,ALGA number(9,2), DATUMS date);

select * from D_ALGA;

ID UZV DZIMUMS VIENIBA ALGA DATUMS------------------------------------------------------------------------------ 1 Koks sieviete 1 150 2002.01.18 2 Koks sieviete 1 160 2002.02.18 3 Koks sieviete 1 160 2002.03.18 4 Koks sieviete 1 160 2002.04.18 5 Koks sieviete 1 170 2002.05.18 6 Celms vīrietis 2 160 2002.01.18 7 Celms vīrietis 2 160 2002.02.18 8 Celms vīrietis 2 170 2002.03.18 9 Celms vīrietis 2 170 2002.04.18 10 Celms vīrietis 2 180 2002.05.18 11 Celms vīrietis 2 180 2002.06.18

select ID, ALGA, 100*CUME_DIST() OVER (PARTITION BY UZV ORDER BY ALGA)from D_ALGAwhere VIENIBA = 1;

ID ALGA 100*CUME_DIST()OVER(PARTITION BY UZV ORDER BY ALGA)---------- ---------- ---------------------------------------------- 1 150 20 2 160 80 3 160 80 4 160 80 5 170 100

Page 36: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

36

Piemēri klona tabulas izmantošanai laika datu gadījumā

select ID, ALGA, LAG(ALGA,1) OVER (PARTITION BY UZV ORDER BY ALGA)from D_ALGAwhere VIENIBA = 1;

ID ALGA LAG(ALGA,1)OVER(PARTITIONBYUZVORDERBYALGA)-------------------------------------------------------------------------------------------------- 1 150 2 160 150 3 160 160 4 160 160 5 170 160

Page 37: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

37

Piemēri klona tabulas izmantošanai laika datu gadījumā

select ID, ALGA, LEAD(ALGA,1) OVER (PARTITION BY UZV ORDER BY ALGA)from D_ALGAwhere VIENIBA = 1;

ID ALGA LEAD(ALGA,1)OVER(PARTITIONBYUZVORDERBYALGA)-------------------------------------------------------------------------------------------------- 1 150 160 2 160 160 3 160 160 4 160 170 5 170

Page 38: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

38

Sample of sparse (rets) dataA typical situation with a sparse dimension is shown in the following example, which computes the weekly sales and year-to-date sales for the product Bounce for weeks 20-30 in 2000 and 2001:

PRODUCT_NAME YEAR WEEK SALES--------------- ---------- ---------- ----------Bounce 2000 20 801Bounce 2000 21 4062.24Bounce 2000 22 2043.16Bounce 2000 23 2731.14Bounce 2000 24 4419.36Bounce 2000 27 2297.29Bounce 2000 28 1443.13Bounce 2000 29 1927.38Bounce 2000 30 1927.38Bounce 2001 20 1483.3Bounce 2001 21 4184.49Bounce 2001 22 2609.19Bounce 2001 23 1416.95Bounce 2001 24 3149.62Bounce 2001 25 2645.98Bounce 2001 27 2125.12Bounce 2001 29 2467.92Bounce 2001 30 2620.17

Page 39: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

39

PRODUCT_NAME YEAR WEEK DENSE_SALES--------------- ---------- ---------- -----------Bounce 2000 20 801Bounce 2000 21 4062.24Bounce 2000 22 2043.16Bounce 2000 23 2731.14Bounce 2000 24 4419.36Bounce 2000 25 0Bounce 2000 26 0Bounce 2000 27 2297.29Bounce 2000 28 1443.13Bounce 2000 29 1927.38Bounce 2000 30 1927.38Bounce 2001 20 1483.3Bounce 2001 21 4184.49Bounce 2001 22 2609.19Bounce 2001 23 1416.95Bounce 2001 24 3149.62Bounce 2001 25 2645.98Bounce 2001 26 0Bounce 2001 27 2125.12Bounce 2001 28 0Bounce 2001 29 2467.92Bounce 2001 30 2620.17

Page 40: Purpose - datubaze.files.wordpress.com  · Web viewBounce 2001 29 2467.92. Bounce 2001 30 2620.17. Analītiskā funkcija NVL() NVL. lets you replace null (returned as a blank) with

40

Analītiskā funkcija NVL()

NVL lets you replace null (returned as a blank) with a string in the results of a query. If expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1.The arguments expr1 and expr2 can have any datatype. If their datatypes are different, then Oracle Database implicitly converts one to the other. If they are cannot be converted implicitly, the database returns an error. The implicit conversion is implemented as follows: If expr1 is character data, then Oracle Database converts expr2 to the datatype of expr1 before comparing them and returns VARCHAR2 in the character set of expr1. If expr1 is numeric, then Oracle determines which argument has the highest numeric precedence, implicitly converts the other argument to that datatype, and returns that datatype.