Friday 1 December 2017

Exponential moving average sql


6 Formatowanie raportów SQLPlus W przeciwnym razie należy ująć myślnik w cudzysłowie, SQLPlus interpretuje myślnik jako łącznik wskazujący, że chcesz kontynuować polecenie w innym wierszu. Formatowanie kolumn NUMBER Podczas wyświetlania kolumn NUMBER można zaakceptować domyślną szerokość wyświetlania SQLPlus lub zmienić za pomocą polecenia COLUMN. Późniejsze sekcje opisują domyślny ekran i sposób jego zmiany za pomocą polecenia COLUMN. Model formatu pozostanie w mocy do momentu wprowadzenia nowego, zresetowania formatu kolumn za pomocą lub wyjścia z SQLPlus. Domyślny wyświetlacz Szerokość kolumny NUMBER równa się szerokości nagłówka lub szerokości FORMAT plus jedno miejsce na znak. którykolwiek jest większy. Jeśli nie użyjesz wyraźnie FORMATU, szerokość kolumn będzie zawsze wynosić co najmniej wartość SET NUMWIDTH. SQLPlus zwykle wyświetla liczby o liczbie cyfr wymaganej dla dokładności, aż do standardowej szerokości wyświetlania określonej przez wartość zmiennej NUMWIDTH polecenia SET (zwykle 10). Jeśli liczba jest większa niż wartość SET NUMWIDTH, SQLPlus zaokrągla liczbę w górę lub w dół do maksymalnej dozwolonej liczby znaków, jeśli to możliwe, lub wyświetla wartości skrótów, jeśli liczba jest zbyt duża. Możesz wybrać inny format dla dowolnej kolumny NUMBER, używając modelu formatu w poleceniu COLUMN. Model formatu jest reprezentacją sposobu wyświetlania liczb w kolumnie, używając 9s do reprezentowania cyfr. Zmiana domyślnego wyświetlania Komenda COLUMN identyfikuje kolumnę, którą chcesz sformatować, oraz model, którego chcesz użyć, jak pokazano: Użyj modeli formatowania, aby dodać przecinki, znaki dolara, nawiasy ostrokątne (wokół wartości ujemnych) i początkowe zera do liczb w podana kolumna. Można także zaokrąglić wartości do określonej liczby miejsc dziesiętnych, wyświetlić znaki minus po prawej stronie wartości ujemnych (zamiast po lewej) i wyświetlić wartości w notacji wykładniczej. Aby użyć więcej niż jednego modelu formatu dla pojedynczej kolumny, połącz pożądane modele w jednym poleceniu COLUMN (patrz przykład 6-4). Zobacz COLUMN, aby uzyskać pełną listę modeli formatów i dalsze szczegóły. Przykład 6-4 Formatowanie kolumny NUMBER Aby wyświetlić WYNAGRODZENIE ze znakiem dolara. przecinek. i cyfrę zero zamiast pustego dla dowolnych wartości zerowych, wprowadź następującą komendę: Teraz ponownie uruchom bieżące zapytanie: Domyślny wyświetlacz Domyślna szerokość kolumn typu danych to szerokość kolumny w bazie danych. Szerokość kolumny typu LONG, CLOB, NCLOB lub XMLType ma domyślnie wartość SET LONGCHUNKSIZE lub SET LONG, w zależności od tego, która wartość jest mniejsza. Domyślna szerokość i format niesformatowanych kolumn DATE w SQLPlus jest określona przez parametr NLSDATEFORMAT bazy danych. W przeciwnym razie domyślna szerokość formatu to A9. Zobacz klauzulę FORMAT komendy COLUMN, aby uzyskać więcej informacji na temat formatowania kolumn DATE. Lewe justowanie jest domyślne dla typów danych. Zmiana domyślnego wyświetlacza Możesz zmienić wyświetlaną szerokość typu danych lub DATE, używając polecenia COLUMN z modelem formatu składającym się z litery A (dla alfanumerycznych), po której następuje liczba określająca szerokość kolumny w znakach. Wewnątrz polecenia COLUMN określ kolumnę, którą chcesz sformatować, i model, którego chcesz użyć: Jeśli określisz szerokość krótszą niż nagłówek kolumny. SQLPlus obcina nagłówek. Aby uzyskać więcej informacji, zobacz polecenie COLUMN. Przykład 6-5 Formatowanie kolumny znaków Aby ustawić szerokość kolumny LASTNAME na cztery znaki i ponownie uruchomić bieżące zapytanie, należy wpisać Jeśli zmienna WRAP polecenia SET jest ustawiona na ON (wartość domyślna), nazwy pracowników są zawijane do następna linia po czwartym znaku, jak pokazano w Przykładzie 6-5, Formatowanie kolumny postaci. Jeśli WRAP jest ustawione na WYŁ., Nazwy są obcinane (obcięte) po czwartym znaku. Zmienna systemowa WRAP kontroluje wszystkie kolumny, które można zastąpić ustawieniem WRAP dla danej kolumny za pomocą WRAPPED. WORDWRAPPED. i TRUNCATED klauzul polecenia COLUMN. Zobacz komendę COLUMN, aby uzyskać więcej informacji na temat tych klauzul. Będziesz używał klauzuli WORDWRAPPED COLUMN w dalszej części tego rozdziału. NCLOB lub wielobajtowych kolumn CLOB nie można sformatować za pomocą opcji WORDWRAPPED. Jeśli formatujesz kolumnę CLOB lub kolumnę wielobajtową za pomocą COLUMN WORDWRAPPED, dane kolumny zachowują się tak, jakby zamiast niej zastosowano COLUMN WRAPPED. Nagłówek kolumny jest obcięty bez względu na ustawienie WRAP lub klauzule komendy COLUMN. Teraz zwróć kolumnę do poprzedniego formatu: Przykład 6-6 Formatowanie kolumny XMLType Przed zilustrowaniem sposobu formatowania kolumny XMLType, musisz utworzyć tabelę z definicją kolumny XMLType i wstawić niektóre dane do tabeli. Możesz utworzyć kolumnę XMLType, tak jak każdą inną kolumnę zdefiniowaną przez użytkownika. Aby utworzyć tabelę zawierającą kolumnę XMLType, wpisz Aby wstawić nowy rekord zawierający wartości warehouseid i warehousespec do nowej tabeli magazynów, wprowadź Aby ustawić szerokość kolumny XMLType na 20 znaków, a następnie wybierz kolumnę XMLType, wpisz Ukrywanie i przywracanie atrybutów wyświetlania kolumny Możesz ukryć i przywrócić atrybuty wyświetlania, które dałeś określonej kolumnie. Aby ukryć atrybuty wyświetlania kolumn, wprowadź polecenie COLUMN w następującej formie: WYŁ. Mówi SQLPlus, aby używał domyślnych atrybutów wyświetlania dla kolumny, ale nie usuwa atrybutów zdefiniowanych przez polecenie COLUMN. Aby przywrócić atrybuty zdefiniowane przez COLUMN. Użyj klauzuli ON: Drukowanie linii znaków po zawijanych wartościach kolumn Jak widać, program SQLPlus domyślnie zawija wartości kolumn do dodatkowych wierszy, gdy wartość nie pasuje do szerokości kolumny. Jeśli chcesz wstawić separator rekordów (linię znaków lub pustą linię) po każdym zawiniętym wierszu wyniku (lub po każdym wierszu), użyj zmiennych RECSEP i RECSEPCHAR polecenia SET. RECSEP określa, kiedy drukowana jest linia znaków, ustawiasz RECSEP na KAŻDĄ, aby drukować po każdej linii, WRAPPED, aby drukować po zawiniętych liniach, oraz na WYŁ, aby wyłączyć drukowanie. Domyślnym ustawieniem RECSEP jest WRAPPED. RECSEPCHAR ustawia znak drukowany w każdym wierszu. Możesz ustawić RECSEPCHAR na dowolny znak. Możesz chcieć zawrzeć całe słowa do dodatkowych linii, gdy wartość kolumny zawija się do dodatkowych linii. Aby to zrobić, użyj klauzuli WORDWRAPPED komendy COLUMN, jak pokazano: Przykład 6-9 Drukowanie linii znaków po zawijanych wartościach kolumn Aby wydrukować linię kresek po każdej wartości kolumny owiniętej, wprowadź polecenia: Na koniec wpisz następujące zapytanie : Teraz ogranicz szerokość JOBTITLE kolumny i powiedz SQLPlus, aby w razie potrzeby zawijał całe wyrazy do dodatkowych wierszy: Jeśli ustawisz RECSEP na EACH, SQLPlus wypisze linię znaków po każdym wierszu (po każdym wydziale, dla powyższego przykładu). Przed kontynuowaniem, ustaw RECSEP na WYŁ, aby wyłączyć drukowanie separatorów rekordów: Wyjaśnienie swojego raportu z odstępami i liniami podsumowania Kiedy używasz klauzuli ORDER BY w poleceniu SQL SELECT, wiersze o tej samej wartości w zamówionej kolumnie (lub wyrażeniu) są wyświetlane razem na wyjściu. Możesz zwiększyć użyteczność tego wyniku dla użytkownika, używając poleceń SQLPlus BREAK i COMPUTE do tworzenia podzbiorów rekordów i dodawania spacji lub linii podsumowania po każdym podzbiorze. Kolumna określona w poleceniu BREAK nosi nazwę kolumny podziału. Uwzględniając kolumnę przerwania w klauzuli ORDER BY, tworzysz znaczące podzestawy rekordów w wynikach. Następnie możesz dodać formatowanie do podzbiorów w ramach tego samego polecenia BREAK i dodać linię podsumowującą (zawierającą sumy, średnie i tak dalej), określając kolumnę przerwania w poleceniu KOMPUTUJ. Aby uczynić ten raport bardziej przydatnym, użyłbyś BREAK, aby ustawić DEPARTMENTID jako kolumnę przerwania. Poprzez BREAK możesz ukryć zduplikowane wartości w DEPARTMENTID i umieścić puste wiersze lub rozpocząć nową stronę między działami. Możesz użyć BREAK w połączeniu z COMPUTE, aby obliczyć i wydrukować podsumowanie wierszy zawierających całkowite wynagrodzenie dla każdego działu i dla wszystkich działów. Można również wydrukować wiersze podsumowania zawierające średnią, maksymalną, minimalną, odchylenie standardowe, wariancję lub liczbę wierszy. Pomijanie zduplikowanych wartości w przerywanych kolumnach Polecenie PRZERWA usuwa domyślnie zduplikowane wartości w kolumnie lub wyrażeniu, którego nazwę. Tak więc, aby pominąć zduplikowane wartości w kolumnie określonej w klauzuli ORDER BY, użyj polecenia BREAK w najprostszej formie: Ilekroć podasz kolumnę lub wyrażenie w poleceniu BREAK, użyj klauzuli ORDER BY określającej tę samą kolumnę lub wyrażenie. Jeśli tego nie zrobisz, przerwy będą występować za każdym razem, gdy zmieni się wartość kolumny. Przykład 6-10 Pomijanie zduplikowanych wartości w kolumnie podziału Aby zablokować wyświetlanie zduplikowanych numerów działów w przedstawionych wynikach zapytania, wprowadź następujące polecenia: W przypadku następującego zapytania (które jest bieżącym zapytaniem przechowywanym w buforze): Możesz chcieć wstaw puste wiersze lub pustą stronę po każdym wierszu. Aby pominąć n wierszy po każdym wierszu, użyj PRZERWY w następującej formie: Aby pominąć stronę po każdym wierszu, użyj SKIP PAGE nie powoduje wygenerowania fizycznego znaku podziału strony, chyba że określono również NEWPAGE 0. Używanie wielu technik odstępowania Załóżmy masz więcej niż jedną kolumnę w klauzuli ORDER BY i chcesz wstawić spację po zmianie wartości każdej kolumny. Każda wprowadzona komenda BREAK zastępuje poprzednią. Tak więc, jeśli chcesz użyć różnych technik odstępów w jednym raporcie lub wstawić spację po zmianie wartości w więcej niż jednej zamówionej kolumnie, musisz określić wiele kolumn i działań w jednym poleceniu BREAK. Przykład 6-12 Łączenie technik rozmieszczania Wpisz następujące polecenie: Teraz, aby pominąć stronę, gdy wartość IDENTYFIKATORU IDENTYFIKATORA zmienia się, i jedną linię, gdy wartość zmiany JOBID ulegnie zmianie, wprowadź następującą komendę: Aby pokazać, że SKIP PAGE odniosła skutek, utwórz TTITLE z numerem strony: Uruchom nowe zapytanie, aby zobaczyć wyniki: Wyświetlanie i usuwanie definicji przerw Przed kontynuowaniem wyłącz wyświetlanie tytułu bez zmiany jego definicji: Możesz wyświetlić bieżącą definicję podziału, wprowadzając polecenie BREAK bez klauzul: Ty można usunąć bieżącą definicję przerwania, wprowadzając polecenie CLEAR z klauzulą ​​BREAKS: Możesz chcieć umieścić polecenie CLEAR BREAKS na początku każdego skryptu, aby upewnić się, że wcześniej wprowadzone polecenia BREAK nie wpłyną na zapytania uruchamiane w danym pliku. Obliczanie linii podsumowania podczas zmiany wartości kolumn łamania Jeśli uporządkujesz wiersze raportu na podzbiory za pomocą polecenia BREAK, możesz wykonywać różne obliczenia na wierszach każdego podzbioru. Robisz to za pomocą funkcji polecenia SQLPlus COMPUTE. Użyj poleceń PRZERWA i KOMPUTUJ razem w następujących formach: Możesz dodać wiele kolumn przerwania i działań, takich jak pomijanie wierszy w poleceniu PRZERWANIE, o ile kolumna, której nazwę po ON w poleceniu KOMPUTOWANIE pojawi się również po WŁĄCZENIU w PRZERWA rozkaz. Aby uwzględnić wiele kolumn przerwania i akcji w BREAK, gdy używa się go w połączeniu z KOMPUTEREM, użyj tych poleceń w następujących postaciach: Polecenie COMPUTE nie działa bez odpowiedniego polecenia BREAK. Możesz KORZYSTAĆ z NUMBER kolumn i, w niektórych przypadkach, ze wszystkich typów kolumn. Aby uzyskać więcej informacji, patrz komenda COMPUTE. Poniższa tabela zawiera listę funkcji obliczeniowych i ich efektów. Tabela 6-1 Funkcje obliczeniowe Funkcja określona w poleceniu KOMPUTER dotyczy wszystkich kolumn wprowadzonych po OF i przed ON. Obliczone wartości są drukowane w oddzielnym wierszu, gdy zmienia się wartość zamówionej kolumny. Etykiety dla obliczeń typu ON RAPORT i ON ROW pojawiają się w pierwszej kolumnie, w przeciwnym razie pojawiają się w kolumnie określonej w klauzuli ON. Możesz zmienić etykietę obliczeniową za pomocą etykiety COMPUTE LABEL. Jeśli nie zdefiniujesz etykiety dla wyliczonej wartości, SQLPlus wypisze słowo kluczowe nieskodowane. Etykieta obliczeniowa może zostać wyłączona przy użyciu opcji NOPRINT polecenia COLUMN w kolumnie podziału. Aby uzyskać więcej informacji, zobacz polecenie COMPUTE. Jeśli użyjesz opcji NOPRINT dla kolumny, na której wykonywane jest polecenie COMPUTE, wynik COMPUTE również zostanie wyłączony. Przykład 6-13 Obliczanie i drukowanie sum częściowych Aby obliczyć sumę WYNAGRODZENIA według działu, najpierw wyświetl aktualną definicję BREAK: która wyświetla bieżące definicje BREAK: Teraz wprowadź następującą komendę COMPUTE i uruchom bieżące zapytanie: Aby obliczyć sumę wynagrodzeń dla działów 10 i 20 bez drukowania etykiety obliczeniowej: Aby obliczyć wynagrodzenie na samym końcu raportu: Podczas ustalania formatu kolumny NUMBER należy uwzględnić wielkość sum zawartych w raporcie. Obliczanie linii podsumowania na końcu raportu Możesz obliczyć i wydrukować linie podsumowania na podstawie wszystkich wartości w kolumnie, używając BREAK i COMPUTE w następujących postaciach: Przykład 6-14 Obliczanie i drukowanie sumy całkowitej Aby obliczyć i wydrukować sumę całkowitą wynagrodzeń dla wszystkich sprzedawców i zmienić etykietę obliczeniową, najpierw wprowadź następujące komendy BREAK i COMPUTE: Następnie wprowadź i uruchom nowe zapytanie: Aby wydrukować sumę całkowitą (lub średnią średnią, najwyższą wartość maksymalną itd.) oprócz sumy częściowe (lub średnie podrzędne, i tak dalej) zawierają kolumnę z przerwami i klauzulę WŁĄCZENIA w komendzie BREAK. Następnie wprowadź jedną komendę COMPUTE dla kolumny podziału i inną dla obliczenia ON RAPORT: Obliczanie wielu wartości podsumowania i linii Możesz obliczyć i wydrukować ten sam typ wartości podsumowania na różnych kolumnach. Aby to zrobić, wprowadź oddzielne polecenie COMPUTE dla każdej kolumny. Przykład 6-15 Obliczanie tego samego rodzaju wartości sumarycznej w różnych kolumnach Aby wydrukować sumę wynagrodzeń i prowizji dla wszystkich sprzedawców, najpierw wprowadź następujące polecenie COMPUTE: Nie musisz wprowadzać BREAK komendy BREAK wprowadzonej w przykładzie 6 -14, Computing i drukowanie Grand Total nadal obowiązuje. Teraz zmień pierwszy wiersz kwerendy wyboru tak, aby zawierał COMMISSIONPCT: Na koniec uruchom poprawione zapytanie, aby zobaczyć wyniki: Możesz również wydrukować wiele linii podsumowania w tej samej kolumnie podziału. Aby to zrobić, dołącz funkcję dla każdej linii podsumowania w poleceniu KOMPUTUJ w następujący sposób: Jeśli umieścisz wiele kolumn po OF i przed ON, program COMPUTE oblicza i drukuje wartości dla każdej określonej kolumny. Przykład 6-16 Obliczanie wielu linii podsumowujących w tej samej kolumnie podziału Aby obliczyć średnią i sumę wynagrodzeń dla działu sprzedaży, najpierw wprowadź następujące komendy BREAK i COMPUTE: Teraz wprowadź i uruchom następujące zapytanie: Wyświetlanie i usuwanie definicji WYKRESÓW może wyświetlić listę twoich aktualnych definicji COMPUTE, wpisując polecenie COMPUTE bez klauzul: Przykład 6-17 Usuwanie definicji KOMPUTU Aby usunąć wszystkie definicje ZBIORU i dołączoną definicję BREAK, wprowadź następujące polecenia: Możesz chcieć umieścić polecenia WYCZYŚĆ BREAKS i WYCZYŚĆ KOMPUTERY na początku każdego skryptu, aby upewnić się, że wcześniej wprowadzone polecenia BREAK i COMPUTE nie wpłyną na zapytania uruchamiane w danym pliku. Definiowanie tytułów i wymiarów strony i raportu Strona ze słowem odnosi się do ekranu pełnego informacji na ekranie lub na stronie wydruku wydrukowanego w kolejce. Możesz umieścić górne i dolne tytuły na każdej stronie, ustawić liczbę wierszy na stronę i określić szerokość każdej linii. Słowo raport odnosi się do kompletnych wyników zapytania. Możesz również umieścić nagłówki i stopki w każdym raporcie i sformatować je w taki sam sposób, jak tytuły górny i dolny na stronach. Ustawianie tytułów i nagłówków górnych i dolnych oraz nagłówków i stopek Jak już zauważyłeś, możesz ustawić tytuł wyświetlany u góry każdej strony raportu. Możesz także ustawić tytuł, który będzie wyświetlany u dołu każdej strony. Polecenie TTITLE definiuje górny tytuł, komenda BTITLE definiuje dolny tytuł. Możesz także ustawić nagłówek i stopkę dla każdego raportu. Polecenie REPHEADER definiuje nagłówek raportu, a polecenie REPFOOTER definiuje stopkę raportu. Komenda TTITLE, BTITLE, REPHEADER lub REPFOOTER składa się z nazwy polecenia, po której następuje jedna lub więcej klauzul określających pozycję lub format oraz wartość CHAR, którą chcesz umieścić na tej pozycji lub podać ten format. Możesz dołączyć wiele zestawów klauzul i wartości CHAR: Aby zapoznać się z opisami wszystkich klauzul TTITLE, BTITLE, REPHEADER i REPFOOTER, zobacz komendę TTITLE i polecenie REPHEADER. Przykład 6-18 Umieszczanie górnego i dolnego tytułu na stronie Aby umieścić tytuły u góry i na dole każdej strony raportu, wpisz Teraz uruchom bieżące zapytanie: Aby ukryć nagłówek raportu bez zmiany jego definicji, wprowadź Elementy pozycji Pozycjonowanie raport z poprzednich ćwiczeń może wyglądać atrakcyjniej, jeśli nadasz nazwę firmy większy nacisk i umieszczasz typ raportu oraz nazwę działu na obu końcach oddzielnej linii. Może to również pomóc w zmniejszeniu rozmiaru linii, a tym samym w dokładniejszym wycentrowaniu tytułów wokół danych. Zmiany można wprowadzić, dodając niektóre klauzule do komendy TTITLE i resetując zmienną systemową LINESIZE. jak pokazuje poniższy przykład. Możesz formatować nagłówki i stopki raportu w taki sam sposób, jak BTITLE i TTITLE, używając poleceń REPHEADER i REPFOOTER. Przykład 6-20 Pozycjonowanie elementów tytułowych Aby ponownie wyświetlić raport personelu z przeniesionym górnym tytułem, wprowadź następujące polecenia: LEWO. DOBRZE. a klauzule CENTER umieszczają następujące wartości na początku, końcu i środku linii. Klauzula SKIP informuje SQLPlus, aby przesunął się w dół o jedną lub więcej linii. Zauważ, że nie ma więcej miejsca między ostatnim wierszem wyników a dolnym tytułem. Ostatnia linia dolnego tytułu zostanie wydrukowana w ostatnim wierszu strony. Wielkość odstępu między ostatnim wierszem raportu a dolnym tytułem zależy od ogólnego rozmiaru strony, liczby linii zajmowanych przez tytuł główny i liczby wierszy na danej stronie. W powyższym przykładzie górny tytuł zajmuje trzy dodatkowe wiersze niż górny tytuł z poprzedniego przykładu. Nauczysz się ustawiać liczbę linii na stronie w dalszej części tego rozdziału. Aby zawsze wyświetlać n pustych linii przed dolnym tytułem, użyj klauzuli SKIP n na początku komendy BTITLE. Na przykład, aby pominąć jedną linię przed dolnym tytułem w powyższym przykładzie, możesz wprowadzić następujące polecenie: Wcięcie elementu tytułu Możesz użyć klauzuli COL w TTITLE lub BTITLE, aby wcięcić element tytułu określoną liczbę spacji. Na przykład COL 1 umieszcza następujące wartości w pierwszym położeniu znaku, a więc jest równoważne LEWYM lub wcięciu zerowemu. COL 15 umieszcza element tytułu w 15. pozycji znaku, wcinając go 14 spacji. Przykład 6-21 Wcięcie elementu tytułowego Aby wydrukować nazwę firmy wyrównaną do lewej z nazwą raportu, z wcięciem pięciu spacji w następnym wierszu, wprowadź Teraz ponownie uruchom bieżące zapytanie, aby zobaczyć wyniki: Wyświetlanie, tłumienie i Przywracanie definicji tytułu strony Do listy definicji tytułu strony, wprowadź odpowiednie polecenie tytułu bez klauzul: Aby pominąć definicję tytułu, wprowadź: Te polecenia powodują, że SQLPlus przestaje wyświetlać tytuły w raportach, ale nie usuwa bieżących definicji tytułów. Możesz przywrócić bieżące definicje, wprowadzając: Wyświetlanie wartości kolumn w tytułach Możesz utworzyć raport masterdetail, który wyświetla zmieniającą się wartość kolumny głównej u góry każdej strony z wynikami zapytania szczegółowego dla tej wartości pod spodem. Możesz odwołać się do wartości kolumny w górnym tytule, przechowując żądaną wartość w zmiennej i odwołując się do zmiennej w komendzie TTITLE. Aby zdefiniować zmienną, użyj następującej formy polecenia COLUMN: Należy uwzględnić kolumnę główną w klauzuli ORDER BY i komendzie BREAK, używając klauzuli SKIP PAGE. Przykład 6-24 Tworzenie raportu MasterDetail Załóżmy, że chcesz utworzyć raport wyświetlający dwa różne numery pracownicze menedżerów, każdy u góry oddzielnej strony, oraz osoby raportujące do menedżera na tej samej stronie co numer pracownika menedżera. Najpierw utwórz zmienną MGRVAR, aby zachować wartość bieżącego numeru pracownika menedżera: ponieważ w tytule wyświetlają się tylko numery pracowników menedżerów, nie należy ich drukować jako części szczegółów. Wprowadzona powyżej klauzula NOPRINT mówi SQLPlus, aby nie drukał kolumny MANAGERID. Następnie umieść etykietę i wartość w tytule strony, wprowadź poprawne polecenie BREAK i usuń dolny tytuł z ostatniego przykładu: Na koniec wprowadź i uruchom następujące zapytanie: Jeśli chcesz wydrukować wartość kolumny W dolnej części strony możesz użyć polecenia COLUMN w następującej formie: SQLPlus wypisuje dolny tytuł jako część procesu przechodzenia do nowego pagemdash po znalezieniu nowej wartości dla kolumny głównej. Dlatego jeśli po prostu odwołujesz się do NEWVALUE kolumny głównej, otrzymasz wartość dla następnego zestawu szczegółów. OLDVALUE zapamiętuje wartość kolumny głównej, która obowiązywała przed rozpoczęciem podziału strony. Wyświetlanie bieżącej daty w tytułach Można oczywiście datować raporty, wpisując po prostu wartość w tytule. Jest to zadowalające dla raportów ad hoc, ale jeśli chcesz wielokrotnie uruchamiać ten sam raport, prawdopodobnie wolałbyś, aby data była wyświetlana automatycznie po uruchomieniu raportu. Możesz to zrobić, tworząc zmienną do przechowywania bieżącej daty. Możesz odwołać się do predefiniowanej zmiennej zastępczej DATE, aby wyświetlić bieżącą datę w tytule, tak jak każdą inną zmienną. Model formatu daty zawarty w pliku LOGIN lub w instrukcji SELECT określa format, w którym SQLPlus wyświetla datę. Więcej informacji na temat modeli formatu daty można znaleźć w podręczniku SQL Database Reference. Zobacz Modyfikowanie pliku LOGIN, aby uzyskać więcej informacji o pliku LOGIN. Możesz również wprowadzić te polecenia interaktywnie. Aby uzyskać więcej informacji, patrz KOLUMNA. Ustawianie wymiarów strony Zazwyczaj strona raportu zawiera liczbę pustych wierszy ustawioną w zmiennej NEWPAGE polecenia SET, tytuł u góry, nagłówki kolumn, wyniki zapytania i tytuł dolny. SQLPlus wyświetla raport, który jest zbyt długi, aby zmieścić się na jednej stronie na kilku kolejnych stronach, z których każda ma własne tytuły i nagłówki kolumn. Ilość danych wyświetlanych przez SQLPlus na każdej stronie zależy od bieżących wymiarów strony. Domyślne wymiary strony używane przez SQLPlus są wyświetlane poniżej: liczba linii przed górnym tytułem: 1 liczba linii na stronę, od góry do dołu strony: 14 liczba znaków w linii: 80 Możesz zmienić te ustawienia aby dopasować rozmiar ekranu komputera lub, w celu drukowania, do rozmiaru arkusza papieru. Możesz zmienić długość strony za pomocą zmiennej systemowej PAGESIZE. Na przykład możesz to zrobić podczas drukowania raportu. Aby ustawić liczbę linii między początkiem każdej strony i górnym tytułem. użyj zmiennej NEWPAGE polecenia SET: Jeśli ustawisz NEWPAGE na zero, SQLPlus pominie zero linii i wyświetli i wydrukuje znak formatu, aby rozpocząć nową stronę. Na większości typów ekranów komputerowych, znak wysunięcia arkusza usuwa ekran i przesuwa kursor na początek pierwszej linii. Gdy drukujesz raport, znak wysunięcia strony powoduje, że drukarka przesuwa się na górę nowego arkusza papieru, nawet jeśli całkowita długość strony jest mniejsza niż papieru. Jeśli ustawisz opcję NEWPAGE na BRAK, SQLPlus nie wydrukuje pustego wiersza lub formularza między stronami raportu. Aby ustawić liczbę linii na stronie, użyj zmiennej PAGESIZE polecenia SET: Możesz zmniejszyć rozmiar linii, aby prawidłowo wyśrodkować tytuł nad wydrukiem, lub możesz zwiększyć rozmiar linii do drukowania na szerokim papierze. Możesz zmienić szerokość linii za pomocą zmiennej LINESIZE polecenia SET: Przykład 6-25 Ustawienie wymiarów strony Aby ustawić rozmiar strony na 66 linii, wyczyść ekran (lub przesuń drukarkę do nowego arkusza papieru) na początku na każdej stronie i ustaw rozmiar linii na 70, wprowadź następujące polecenia: Teraz wprowadź i uruchom poniższe polecenia, aby zobaczyć wyniki: Teraz uruchom następujące zapytanie: Teraz zresetuj PAGESIZE, NEWPAGE i LINESIZE do ich wartości domyślnych: Aby wyświetlić listę bieżące wartości tych zmiennych, użyj polecenia POKAŻ: Poprzez komendę SQLPlus SPOOL. możesz przechowywać wyniki zapytania w pliku lub wydrukować je na domyślnej drukarce komputera. Przechowywanie i drukowanie wyników zapytania Wyślij wyniki zapytania do pliku, jeśli chcesz je edytować za pomocą edytora tekstu przed wydrukowaniem lub dołączyć je do listu, e-maila lub innego dokumentu. Aby przechowywać wyniki zapytania w pliku filemdash i nadal wyświetlać je na ekranie komendy SPOOL w następującej postaci: Jeśli nie podążasz za nazwą pliku z kropką i rozszerzeniem, SPOOL dodaje domyślne rozszerzenie pliku do nazwy pliku, aby go zidentyfikować jako plik wyjściowy. Wartość domyślna różni się w zależności od systemu operacyjnego na większości hostów - LST lub LIS. Rozszerzenie nie jest dołączane podczas buforowania do plików wygenerowanych przez system, takich jak devnull i devstderr. Więcej informacji można znaleźć w dokumentacji Oracle dla danego systemu operacyjnego. SQLPlus kontynuuje buforowanie informacji do pliku, dopóki nie wyłączysz buforowania, używając następującej formy SPOOL: Tworzenie płaskiego pliku Podczas przenoszenia danych między różnymi produktami oprogramowania, czasami konieczne jest użycie płaskiego pliku (plik systemu operacyjnego bez ucieczki znaki, nagłówki lub dodatkowe znaki osadzone). Na przykład, jeśli nie masz Oracle Net, musisz utworzyć płaski plik do użycia z SQLLoader podczas przenoszenia danych z Oracle9 i do Oracle Database 10 g. Aby utworzyć płaski plik za pomocą SQLPlus, musisz najpierw wprowadzić następujące komendy SET: Po wprowadzeniu tych komend użyjesz polecenia SPOOL, jak pokazano w poprzedniej sekcji, aby utworzyć płaski plik. Polecenie SET COLSEP może być przydatne do rozróżnienia kolumn. Aby uzyskać więcej informacji, zobacz polecenie SET. Wysyłanie wyników do pliku Aby zapisać wyniki zapytania w pliku file i nadal wyświetlać je na ekranie komendy SPOOL w następującej formie: SQLPlus przechowuje wszystkie informacje wyświetlane na ekranie po wprowadzeniu polecenia SPOOL w określonym pliku. Wysyłanie wyników do drukarki Aby wydrukować wyniki zapytania. buforuje je do pliku, jak opisano w poprzedniej sekcji. Następnie, zamiast używać polecenia WYŁĄCZ (SPOOL), wprowadź polecenie w następującej formie: SQLPlus zatrzymuje buforowanie i kopiuje zawartość zbioru buforowego do standardowej (domyślnej) drukarki. SPOOL OUT nie usuwa pliku spoola po wydrukowaniu. Przykład 6-26 Wysyłanie wyników kwerend do drukarki Aby wygenerować raport końcowy i buforować i wydrukować wyniki, utwórz skrypt o nazwie EMPRPT zawierający następujące polecenia. Najpierw użyj EDIT, aby utworzyć skrypt za pomocą edytora tekstu systemu operacyjnego. Następnie wprowadź poniższe polecenia do pliku, używając edytora tekstu: Jeśli nie chcesz widzieć danych wyjściowych na ekranie, możesz również dodać SET TERMOUT OFF na początku pliku i SET TERMOUT ON na końcu pliku. plik. Zapisz i zamknij plik w edytorze tekstu (automatycznie powrócisz do SQLPlus). Teraz uruchom skrypt EMPRPT: SQLPlus wyświetla dane wyjściowe na ekranie (chyba że ustawisz TERMOUT na OFF) i buforuje je do pliku TEMP: Wprowadzenie W poprzednim artykule przyjrzano się, czym są średnie ruchome i jak je obliczyć. W tym artykule przyjrzymy się teraz, jak wdrożyć je w Web Intelligence. Użyta tutaj formuła jest zgodna z wersją XIr3 SAP BOE, jednak niektóre formuły mogą działać w poprzednich wersjach, jeśli są dostępne. Zacznijmy od tego, jak obliczyć prostą średnią ruchomą przed obejrzeniem formularzy ważonych i wykładniczych. Przykładowe przykłady Poniższe przykłady wykorzystują ten sam zestaw danych, który jest danymi o cenach akcji w pliku Excel, który można pobrać. Pierwszą kolumną w pliku jest dzień ceny akcji, a następnie kolumny ceny otwarcia, najwyższa cena w danym dniu, najniższa cena, cena zamknięcia, wolumen i skorygowana cena zamknięcia. We8217ll wykorzysta cenę zamknięcia w poniższej analizie wraz z obiektem Date. Prosta średnia ruchoma Istnieje kilka sposobów obliczania prostych średnich kroczących. Jedną z opcji jest użycie funkcji Poprzedni w celu uzyskania wartości poprzedniego wiersza. Na przykład poniższa formuła oblicza średnią ruchomą z naszej końcowej ceny akcji dla średniej ruchomej zestawu danych o rozmiarze 3, Jest to dość prosta formuła, ale oczywiste jest, że nie jest to praktyczne, gdy mamy dużą liczbę okresów, w których możemy dokonać użycie formuły RunningSum i zestawu danych o rozmiarze N mamy W końcu mamy trzecią technikę, która chociaż jest bardziej skomplikowana, może mieć lepszą wydajność, ponieważ oblicza nową wartość na podstawie poprzedniej wartości, zamiast dwóch działających sum na pełnych danych zestaw. Ta formuła działa jednak dopiero po N-tym punkcie w całym zestawie danych, a ponieważ odnosi się do poprzedniej wartości, musimy również ustawić wartość początkową. Poniżej znajduje się pełna formuła stosowana w naszej analizie cen akcji, w której średnia krocząca wynosi 15 dni. Data 1252017 to 15 punkt danych w naszym zestawie danych, więc dla tego punktu obliczamy normalną średnią z wykorzystaniem RunningSum. Dla wszystkich dat poza tą wartością stosujemy naszą formułę SMA i pozostawiamy puste wszystkie daty przed tą datą. Ryc. 1 poniżej przedstawia wykres w Web Intelligence wyświetlający nasze dane o cenach akcji za pomocą prostej średniej ruchomej. Rysunek 1. Dokument Web Intelligence wyświetlający średnią ruchomą średnią ważoną ruchomą Ważoną średnią ruchomą z okresem 3 jest taka, jak w przypadku naszej pierwszej prostej formuły średniej ruchomej powyżej, jest to praktyczne tylko dla małej liczby okresów. Nie udało mi się jeszcze znaleźć prostej formuły, która mogłaby być stosowana w większych okresach średniej ruchomej. Matematyczne to jest możliwe, ale ograniczenia dzięki Web Intelligence oznaczają, że te wzory nie konwertują. Jeśli ktokolwiek jest w stanie to zrobić, chciałbym usłyszeć Poniższy rysunek jest WMA z okresu 6 wdrożonego w Web Intelligence. Rysunek 2. Dokument Web Intelligence ważonej średniej ruchomej wykładniczej Średnia ruchoma wykładnicza jest dość prosta do wdrożenia w Web Intelligence i dlatego jest odpowiednią alternatywą dla ważonej średniej ruchomej. Podstawowa formuła jest tutaj We8217ve zakodowana 0.3 jako nasza wartość alfa. Stosujemy tę formułę tylko dla okresów większych niż nasz drugi okres, więc możemy użyć instrukcji if, aby je odfiltrować. Dla naszego pierwszego i drugiego okresu możemy użyć poprzedniej wartości, a więc naszą ostateczną formułą dla EMA jest: Poniżej znajduje się przykład EMA stosowanego do naszych danych giełdowych. Rysunek 3. Dokument Web Intelligence wyświetla średnią ewolucyjną ruchy wejściowe Ponieważ nasza formuła EMA nie opiera się na wielkości okresu średniej ruchomej, a naszą jedyną zmienną jest alfa, możemy użyć Kontroli wejściowej, aby umożliwić użytkownikowi dostosowanie wartości alfa. Aby to zrobić, utwórz nową zmienną o nazwie 8216alpha8217 i zdefiniuj jej formułę8282, Uaktualnij naszą formułę EMA, Utwórz nowy kontrolkę wprowadzania, wybierając naszą zmienną alfa jako obiekt raportu kontroli wejścia Użyj prostego suwaka i ustaw następujące właściwości, Po zakończeniu should be able to move the slider and immediately see the changes to the trend line in the chart Conclusion We looked at how to implement three types of moving average in Web Intelligence and although all were possible the Exponential Moving Average is probably the easiest and most flexible . I hope you found this article interesting and as always any feedback is very welcome. Post navigation Leave a Reply Cancel reply You must be logged in to post a comment. The trick to Weighted Moving Average (WMA) is you have to create a variable which represents the numerators of WMA (see Wikipedia for reference.) This should look like the following: Previous(Self) (n Close) 8211 ( Previous(RunningSum(Close)) 8211 Previous(RunningSum(Close)n1) where n is the number of periods. Then the actual WMA8217s formula would be like this: Numerator (n (n 1) 2) where Numerator is the variable you created earlier.22 SQL for Analysis and Reporting Oracle has enhanced SQLs analytical processing capabilities by introducing a new family of analytic SQL functions. These analytic functions enable you to calculate: Rankings and percentiles Moving window calculations Linear regression statistics Ranking functions include cumulative distributions, percent rank, and N-tiles. Moving window calculations allow you to find moving and cumulative aggregations, such as sums and averages. Laglead analysis enables direct inter-row references so you can calculate period-to-peri od changes. Firstlast analysis enables you to find the first or last value in an ordered group. Other enhancements to SQL include the CASE expression and partitioned outer join. CASE expressions provide if-then logic useful in many situations. Partitioned outer join is an extension to ANSI outer join syntax that allows users to selectively densify certain dimensions while keeping others sparse. This allows reporting tools to selectively densify dimensions, for example, the ones that appear in their cross-tabular reports while keeping others sparse. To enhance performance, analytic functions can be parallelized: multiple processes can simultaneously execute all of these statements. These capabilities make calculations easier and more efficient, thereby enhancing database performance, scalability, and simplicity. Analytic functions are classified as described in Table 22-1 . Table 22-1 Analytic Functions and Their Uses To perform these operations, the analytic functions add several new elements to SQL processing. These elements build on existing SQL to allow flexible and powerful calculation expressions. With just a few exceptions, the analytic functions have these new elements. The processing flow is represented in Figure 22-1 . Figure 22-1 Processing Order The essential concepts used in analytic functions are: Query processing using analytic functions takes place in three stages. First, all joins, WHERE. GROUP BY and HAVING clauses are performed. Second, the result set is made available to the analytic functions, and all their calculations take place. Third, if the query has an ORDER BY clause at its end, the ORDER BY is processed to allow for precise output ordering. The processing order is shown in Figure 22-1 . Result set partitions The analytic functions allow users to divide query result sets into groups of rows called partitions. Note that the term partitions used with analytic functions is unrelated to the table partitions feature. Throughout this chapter, the term partitions refers to only the meaning related to analytic functions. Partitions are created after the groups defined with GROUP BY clauses, so they are available to any aggregate results such as sums and averages. Partition divisions may be based upon any desired columns or expressions. A query result set may be partitioned into just one partition holding all the rows, a few large partitions, or many small partitions holding just a few rows each. For each row in a partition, you can define a sliding window of data. This window determines the range of rows used to perform the calculations for the current row. Window sizes can be based on either a physical number of rows or a logical interval such as time. The window has a starting row and an ending row. Depending on its definition, the window may move at one or both ends. For instance, a window defined for a cumulative sum function would have its starting row fixed at the first row of its partition, and its ending row would slide from the starting point all the way to the last row of the partition. In contrast, a window defined for a moving average would have both its starting and end points slide so that they maintain a constant physical or logical range. A window can be set as large as all the rows in a partition or just a sliding window of one row within a partition. When a window is near a border, the function returns results for only the available rows, rather than warning you that the results are not what you want. When using window functions, the current row is included during calculations, so you should only specify ( n -1) when you are dealing with n items. Each calculation performed with an analytic function is based on a current row within a partition. The current row serves as the reference point determining the start and end of the window. For instance, a centered moving average calculation could be defined with a window that holds the current row, the six preceding rows, and the following six rows. This would create a sliding window of 13 rows, as shown in Figure 22-2 . Figure 22-2 Sliding Window Example Ranking, Windowing, and Reporting Functions This section illustrates the basic analytic functions for ranking, windowing, and reporting. Sample Linear Regression Calculation In this example, we compute an ordinary-least-squares regression line that expresses the quantity sold of a product as a linear function of the products list price. The calculations are grouped by sales channel. The values SLOPE. INTCPT. RSQR are slope, intercept, and coefficient of determination of the regression line, respectively. The (integer) value COUNT is the number of products in each channel for whom both quantity sold and list price data are available. Statistical Aggregates Oracle provides a set of SQL statistical functions and a statistics package, DBMSSTATFUNCS. This section lists some of the new functions along with basic syntax. Descriptive Statistics You can calculate the following descriptive statistics: Median of a Data Set Mode of a Data Set You can calculate the following parametric statistics: Spearmans rho Coefficient Kendalls tau-b Coefficient In addition to the functions, this release has a PLSQL package, DBMSSTATFUNCS. It contains the descriptive statistical function SUMMARY along with functions to support distribution fitting. The SUMMARY function summarizes a numerical column of a table with a variety of descriptive statistics. The five distribution fitting functions support normal, uniform, Weibull, Poisson, and exponential distributions. User-Defined Aggregates Oracle offers a facility for creating your own functions, called user-defined aggregate functions. These functions are written in programming languages such as PLSQL, Java, and C, and can be used as analytic functions or aggregates in materialized views. See Oracle Database Data Cartridge Developers Guide for further information regarding syntax and restrictions. The advantages of these functions are: Highly complex functions can be programmed using a fully procedural language. Higher scalability than other techniques when user-defined functions are programmed for parallel processing. Object data types can be processed. As a simple example of a user-defined aggregate function, consider the skew statistic. This calculation measures if a data set has a lopsided distribution about its mean. It will tell you if one tail of the distribution is significantly larger than the other. If you created a user-defined aggregate called udskew and applied it to the credit limit data in the prior example, the SQL statement and results might look like this: Before building user-defined aggregate functions, you should consider if your needs can be met in regular SQL. Many complex calculations are possible directly in SQL, particularly by using the CASE expression. Staying with regular SQL will enable simpler development, and many query operations are already well-parallelized in SQL. Even the earlier example, the skew statistic, can be created using standard, albeit lengthy, SQL. Pivoting Operations The d ata returned by business intelligence queries is often most usable if presented in a crosstabular format. The pivotclause of the SELECT statement lets you write crosstabulation queries that rotate rows into columns, aggregating data in the process of the rotation. Pivoting is a key technique in data warehouses. In it, you transform multiple rows of input into fewer and generally wider rows in the data warehouse. When pivoting, an aggregation operator is applied for each item in the pivot column value list. The pivot column cannot contain an arbitrary expression. If you need to pivot on an expression, then you should alias the expression in a view before the PIVOT operation. The basic syntax is as follows: To illustrate the use of pivoting, create the following view as a basis for later examples: Example: Pivoting The following statement illustrates a typical pivot on the channel column: Note that the output has created four new aliased columns, DIRECTSALES. INTERNETSALES. CATALOGSALES. and TELESALES. one for each of the pivot values. The output is a sum. If no alias is provided, the column heading will be the values of the IN - list. Pivoting on Multiple Columns You can pivot on more than one column. The following statement illustrates a typical multiple column pivot: Note that this example specifies a multi-column IN - list with column headings designed to match the IN - list members. Pivoting: Multiple Aggregates You can pivot with multiple aggregates, as shown in the following example: Note that the query creates column headings by concatenating the pivot values (or alias) with the alias of the aggregate function, plus an underscore. Distinguishing PIVOT-Generated Nulls from Nulls in Source Data You can distinguish between null values that are generated from the use of PIVOT and those that exist in the source data. The following example illustrates nulls that PIVOT generates. The following query returns rows with 5 columns, column prodid. and pivot resulting columns Q1. Q1COUNTTOTAL. Q2. Q2COUNTTOTAL. For each unique value of prodid. Q1COUNTTOTAL returns the total number of rows whose qtr value is Q1. that is, and Q2COUNTTOTAL returns the total number of rows whose qtr value is Q2 . Assume we have a table sales2 of the following structure: From the result, we know that for prodid 100, there are 2 sales rows for quarter Q1. and 1 sales row for quarter Q2 for prodid 200, there is 1 sales row for quarter Q1. and no sales row for quarter Q2.So, in Q2COUNTTOTAL. you can identify that NULLlt1gt comes from a row in the original table whose measure is of null value, while NULLlt2gt is due to no row being present in the original table for prodid 200 in quarter Q2 . Unpivoting Operations An unpivot does not reverse a PIVOT operation. Instead, it rotates data from columns into rows. If you are working with pivoted data, an UNPIVOT operation cannot reverse any aggregations that have been made by PIVOT or any other means. To illustrate unpivoting, first create a pivoted table that includes four columns, for quarters of the year: The tables contents resemble the following: The following UNPIVOT operation rotates the quarter columns into rows. For each product, there will be four rows, one for each quarter. Note the use of INCLUDE NULLS in this example. You can also use EXCLUDE NULLS. which is the default setting. In addition, you can also unpivot using two columns, as in the following: Wildcard and Subquery Pivoting with XML Operations If you want to use a wildcard argument or subquery in your pivoting columns, you can do so with PIVOT XML syntax. With PIVOT XML, the output of the operation is properly formatted XML. The following example illustrates using the wildcard keyword, ANY. It outputs XML that includes all channel values in salesview : Note that the keyword ANY is available in PIVOT operations only as part of an XML operation. This output includes data for cases where the channel exists in the data set. Also note that aggregation functions must specify a GROUP BY clause to return multiple values, yet the pivotclause does not contain an explicit GROUP BY clause. Instead, the pivotclause performs an implicit GROUP BY . The following example illustrates using a subquery. It outputs XML that includes all channel values and the sales data corresponding to each channel: The output densifies the data to include all possible channels for each product. Data Densification for Reporting Data is normally stored in sparse form. That is, if no value exists for a given combination of dimension values, no row exists in the fact table. However, you may want to view the data in dense form, with rows for all combination of dimension values displayed even when no fact data exist for them. For example, if a product did not sell during a particular time period, you may still want to see the product for that time period with zero sales value next to it. Moreover, time series calculations can be performed most easily when data is dense along the time dimension. This is because dense data will fill a consistent number of rows for each period, which in turn makes it simple to use the analytic windowing functions with physical offsets. Data densification is the process of converting sparse data into dense form. To overcome the problem of sparsity, you can use a partitioned outer join to fill the gaps in a time series or any other dimension. Such a join extends the conventional outer join syntax by applying the outer join to each logical partition defined in a query. Oracle logically partitions the rows in your query based on the expression you specify in the PARTITION BY clause. The result of a partitioned outer join is a UNION of the outer joins of each of the partitions in the logically partitioned table with the table on the other side of the join. Note that you can use this type of join to fill the gaps in any dimension, not just the time dimension. Most of the examples here focus on the time dimension because it is the dimension most frequently used as a basis for comparisons. Partition Join Syntax The syntax for partitioned outer join extends the ANSI SQL JOIN clause with the phrase PARTITION BY followed by an expression list. The expressions in the list specify the group to which the outer join is applied. The following are the two forms of syntax normally used for partitioned outer join: Note that FULL OUTER JOIN is not supported with a partitioned outer join. Sample of Sparse Data A typi cal 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: In this example, we would expect 22 rows of data (11 weeks each from 2 years) if the data were dense. However, we get only 18 rows because weeks 25 and 26 are missing in 2000, and weeks 26 and 28 in 2001. Filling Gaps in Data We can take the sparse data of the preceding query and do a partitioned outer join with a dense set of time data. In the following query, we alias our original query as v and we select data from the times table, which we alias as t. Here we retrieve 22 rows because there are no gaps in the series. The four added rows each have 0 as their Sales value set to 0 by using the NVL function. Note that in this query, a WHERE condition was placed for weeks between 20 and 30 in the inline view for the time dimension. This was introduced to keep the result set small. Filling Gaps in Two Dimensions N-dimensional data is typically displayed as a dense 2-dimensional cross tab of (n - 2) page dimensions. This requires that all dimension values for the two dimensions appearing in the cross tab be filled in. The following is another example where the partitioned outer join capability can be used for filling the gaps on two dimensions: In this query, the WITH subquery factoring clause v1 summarizes sales data at the product, country, and year level. This result is sparse but users may want to see all the country, year combinations for each product. To achieve this, we take each partition of v1 based on product values and outer join it on the country dimension first. This will give us all values of country for each product. We then take that result and partition it on product and country values and then outer join it on time dimension. This will give us all time values for each product and country combination. Filling Gaps in an Inventory Table An inventory table typically tracks quantity of units available for various products. This table is sparse: it only stores a row for a product when there is an event. For a sales table, the event is a sale, and for the inventory table, the event is a change in quantity available for a product. For example, consider the following inventory table: The inventory table now has the following rows: For reporting purposes, users may want to see this inventory data differently. For example, they may want to see all values of time for each product. This can be accomplished using partitioned outer join. In addition, for the newly inserted rows of missing time periods, users may want to see the values for quantity of units column to be carried over from the most recent existing time period. The latter can be accomplished using analytic window function LASTVALUE value. Here is the query and the desired output: The inner query computes a partitioned outer join on time within each product. The inner query densifies the data on the time dimension (meaning the time dimension will now have a row for each day of the week). However, the measure column quantity will have nulls for the newly added rows (see the output in the column quantity in the following results. The outer query uses the analytic function LASTVALUE. Applying this function partitions the data by product and orders the data on the time dimension column ( timeid ). For each row, the function finds the last non-null value in the window due to the option IGNORE NULLS. which you can use with both LASTVALUE and FIRSTVALUE. We see the desired output in the column repeatedquantity in the following output: Computing Data Values to Fill Gaps Examples in previous section illustrate how to use partitioned outer join to fill gaps in one or more dimensions. However, the result sets produced by partitioned outer join have null values for columns that are not included in the PARTITION BY list. Typically, these are measure columns. Users can make use of analytic SQL functions to replace those null values with a non-null value. For example, the following q uery computes monthly totals for products 64MB Memory card and DVD-R Discs (product IDs 122 and 136) for the year 2000. It uses partitioned outer join to densify data for all months. For the missing months, it then uses the analytic SQL function AVG to compute the sales and units to be the average of the months when the product was sold. If working in SQLPlus, the following two commands wraps the column headings for greater readability of results: Time Series Calculations on Densified Data Densificatio n is not just for reporting purpose. It also enables certain types of calculations, especially, time series calculations. Time series calculations are easier when data is dense along the time dimension. Dense data has a consistent number of rows for each time periods which in turn make it simple to use analytic window functions with physical offsets. To illustrate, let us first take the example on Filling Gaps in Data. and lets add an analytic function to that query. In the following enhanced version, we calculate weekly year-to-date sales alongside the weekly sales. The NULL values that the partitioned outer join inserts in making the time series dense are handled in the usual way: the SUM function treats them as 0s. Period-to-Period Comparison for One Time Level: Example How do we use this feature to compare values across time periods Specifically, how do we calculate a year-over-year sales comparison at the week level The following query returns on the same row, for each product, the year-to-date sales for each week of 2001 with that of 2000. Note that in this example we start with a WITH clause. This improves readability of the query and lets us focus on the partitioned outer join. If working in SQLPlus, the following command wraps the column headings for greater readability of results: In the FROM clause of the inline view densesales. we use a partitioned outer join of aggregate view v and time view t to fill gaps in the sales data along the time dimension. The output of the partitioned outer join is then processed by the analytic function SUM. OVER to compute the weekly year-to-date sales (the weeklyytdsales column). Thus, the view densesales computes the year-to-date sales data for each week, including those missing in the aggregate view s. The inline view yearoveryearsales then computes the year ago weekly year-to-date sales using the LAG function. The LAG function labeled weeklyytdsalesprioryear specifies a PARTITION BY clause that pairs rows for the same week of years 2000 and 2001 into a single partition. We then pass an offset of 1 to the LAG function to get the weekly year to date sales for the prior year. The outermost query block selects data from yearoveryearsales with the condition yr 2001. and thus the query returns, for each product, its weekly year-to-date sales in the specified weeks of years 2001 and 2000. Period-to-Period Comparison for Multiple Time Levels: Example While the prior example shows us a way to create comparisons for a single time level, it would be even more useful to handle multiple time levels in a single query. For example, we could compare sales versus the prior period at the year, quarter, month and day levels. How can we create a query which performs a year-over-year comparison of year-to-date sales for all levels of our time hierarchy We will take several steps to perform this task. The goal is a single query with comparisons at the day, week, month, quarter, and year level. The steps are as follows: We will create a view called cubeprodtime. which holds a hierarchical cube of sales aggregated across times and products . Then we will create a view of the time dimension to use as an edge of the cube. The time edge, which holds a complete set of dates, will be partitioned outer joined to the sparse data in the view cubeprodtime . Finally, for maximum performance, we will create a materialized view, mvprodtime. built using the same definition as cubeprodtime . For more information regarding hierarchical cubes, see Chapter 21, SQL for Aggregation in Data Warehouses. The materialized view is defined in Step 1 in the following section. Step 1 Create the hierarchical cube view The materialized view shown in the following may already exist in your system if not, create it now. If you must generate it, note that we limit the query to just two products to keep processing time short: Because this view is limited to two products, it returns just over 2200 rows. Note that the column HierarchicalTime contains string representations of time from all levels of the time hierarchy. The CASE expression used for the HierarchicalTime column appends a marker (0, 1. ) to each date string to denote the time level of the value. A 0 represents the year level, 1 is quarters, 2 is months, and 3 is day. Note that the GROUP BY clause is a concatenated ROLLUP which specifies the rollup hierarchy for the time and product dimensions. The GROUP BY clause is what determines the hierarchical cube contents. Step 2 Create the view edgetime, which is a complete set of date values edgetime is the source for filling time gaps in the hierarchical cube using a partitioned outer join. The column HierarchicalTime in edgetime will be used in a partitioned join with the HierarchicalTime column in the view cubeprodtime. The following statement defines edgetime : Step 3 Create the materialized view mvprodtime to support faster performance The materialized view definition is a duplicate of the view cubeprodtime defined earlier. Because it is a duplicate query, references to cubeprodtime will be rewritten to use the mvprodtime materialized view. The following materialized may already exist in your system if not, create it now. If you must generate it, note that we limit the query to just two products to keep processing time short. Step 4 Create the comparison query We have now set the stage for our comparison query. We can obtain period-to-period comparison calculations at all time levels. It requires applying analytic functions to a hierarchical cube with dense data along the time dimension. Some of the calculations we can achieve for each time level are: Sum of sales for prior period at all levels of time. Variance in sales over prior period. Sum of sales in the same period a year ago at all levels of time. Variance in sales over the same period last year. The following example performs all four of these calculations. It uses a partitioned outer join of the views cubeprodtime and edgetime to create an inline view of dense data called densecubeprodtime. The query then uses the LAG function in the same way as the prior single-level example. The outer WHERE clause specifies time at three levels: the days of August 2001, the entire month, and the entire third quarter of 2001. Note that the last two rows of the results contain the month level and quarter level aggregations. Note that to make the results easier to read if you are using SQLPlus, the column headings should be adjusted with the following commands. The commands will fold the column headings to reduce line length: Here is the query comparing current sales to prior and year ago sales: The first LAG function ( salespriorperiod ) partitions the data on gidp. cat. subcat. prod. gidt and orders the rows on all the time dimension columns. It gets the sales value of the prior period by passing an offset of 1. The second LAG function ( salessameperiodprioryear ) partitions the data on additional columns qtrnum. monnum. and daynum and orders it on yr so that, with an offset of 1, it can compute the year ago sales for the same period. The outermost SELECT clause computes the variances. Creating a Custom Member in a Dimension: Example In many analytical SQL tasks, it is helpful to define custom members in a dimension. For instance, you might define a specialized time period for analyses. You can use a partitioned outer join to temporarily add a member to a dimension. Note that the new SQL MODEL clause is suitable for creating more complex scenarios involving new members in dimensions. See Chapter 23, SQL for Modeling for more information on this topic. As an example of a task, what if we want to define a new member for our time dimension We want to create a 13th member of the Month level in our time dimension. This 13th month is defined as the summation of the sales for each product in the first month of each quarter of year 2001. The solution has two steps. Note that we will build this solution using the views and tables created in the prior example. Two steps are required. First, create a view with the new member added to the appropriate dimension. The view uses a UNION ALL operation to add the new member. To query using the custom member, use a CASE expression and a partitioned outer join. Our new member for the time dimension is created with the following view: In this statement, the view timec is defined by performing a UNION ALL of the edgetime view (defined in the prior example) and the user-defined 13th month. The gidt value of 8 was chosen to differentiate the custom member from the standard members. The UNION ALL specifies the attributes for a 13th month member by doing a SELECT from the DUAL table. Note that the grouping id, column gidt. is set to 8, and the quarter number is set to 5. Then, the second step is to use an inline view of the query to perform a partitioned outer join of cubeprodtime with timec. This step creates sales data for the 13th month at each level of product aggregation. In the main query, the analytic function SUM is used with a CASE expression to compute the 13th month, which is defined as the summation of the first months sales of each quarter. The SUM function uses a CASE to limit the data to months 1, 4, 7, and 10 within each year. Due to the tiny data set, with just 2 products, the rollup values of the results are necessarily repetitions of lower level aggregations. For more realistic set of rollup values, you can include more products from the Game Console and Y Box Games subcategories in the underlying materialized view. Miscellaneous Analysis and Reporting Capabilities This section illustrates the following additional analytic capabilities: WIDTHBUCKET Function For a given expression, the WIDTHBUCKET function returns the bucket number that the result of this expression will be assigned after it is evaluated. You can generate equiwidth histograms with this function. Equiwidth histograms divide data sets into buckets whose interval size (highest value to lowest value) is equal. The number of rows held by each bucket will vary. A related function, NTILE. creates equiheight buckets. Equiwidth histograms can be generated only for numeric, date or datetime types. So the first three parameters should be all numeric expressions or all date expressions. Other types of expressions are not allowed. If the first parameter is NULL. the result is NULL. If the second or the third parameter is NULL. an error message is returned, as a NULL value cannot denote any end point (or any point) for a range in a date or numeric value dimension. The last parameter (number of buckets) should be a numeric expression that evaluates to a positive integer value 0, NULL. or a negative value will result in an error. Buckets are numbered from 0 to ( n 1). Bucket 0 holds the count of values less than the minimum. Bucket( n 1) holds the count of values greater than or equal to the maximum specified value. WIDTHBUCKET Syntax The WIDTHBUCKET takes four expressions as parameters. The first parameter is the expression that the equiwidth histogram is for. The second and third parameters are expressions that denote the end points of the acceptable range for the first parameter. The fourth parameter denotes the number of buckets. Consider the following data from table customers. that shows the credit limits of 17 customers. This data is gathered in the query shown in Example 22-24 . In the table customers. the column custcreditlimit contains values between 1500 and 15000, and we can assign the values to four equiwidth buckets, numbered from 1 to 4, by using WIDTHBUCKET (custcreditlimit, 0, 20000, 4). Ideally each bucket is a closed-open interval of the real number line, for example, bucket number 2 is assigned to scores between 5000.0000 and 9999.9999. sometimes denoted 5000, 10000) to indicate that 5,000 is included in the interval and 10,000 is excluded. To accommodate values outside the range 0, 20,000), values less than 0 are assigned to a designated underflow bucket which is numbered 0, and values greater than or equal to 20,000 are assigned to a designated overflow bucket which is numbered 5 (num buckets 1 in general). See Figure 22-3 for a graphical illustration of how the buckets are assigned. Figure 22-3 Bucket Assignments You can specify the bounds in the reverse order, for example, WIDTHBUCKET ( custcreditlimit. 20000. 0. 4 ). When the bounds are reversed, the buckets will be open-closed intervals. In this example, bucket number 1 is ( 15000,20000 , bucket number 2 is ( 10000,15000 , and bucket number 4, is ( 0 ,5000 . The overflow bucket will be numbered 0 ( 20000. infinity ), and the underflow bucket will be numbered 5 (- infinity. 0 . It is an error if the bucket count parameter is 0 or negative. Example 22-24 WIDTHBUCKET The followin g query shows the bucket numbers for the credit limits in the customers table for both cases where the boundaries are specified in regular or reverse order. We use a range of 0 to 20,000. Linear Algebra Linear algebra is a branch of mathematics with a wide range of practical applications. Many areas have tasks that can be expressed using linear algebra, and here are some examples from several fields: statistics (multiple linear regression and principle components analysis), data mining (clustering and classification), bioinformatics (analysis of microarray data), operations research (supply chain and other optimization problems), econometrics (a nalysis of consumer demand data), and finance (asset allocation problems). Various libraries for linear algebra are freely available for anyone to use. Oracles UTLNLA package exposes matrix PLSQL data types and wrapper PLSQL subprograms for two of the most popular and robust of these libraries, BLAS and LAPACK. Linear algebra depends on matrix manipulation. Performing matrix manipulation in PLSQL in the past required inventing a matrix representation based on PLSQLs native data types and then writing matrix manipulation routines from scratch. This required substantial programming effort and the performance of the resulting implementation was limited. If developers chose to send data to external packages for processing rather than create their own routines, data transfer back and forth could be time consuming. Using the UTLNLA package lets data stay within Oracle, removes the programming effort, and delivers a fast implementation. Example 22-25 Linear Algebra Here is an example of how Oracles linear algebra support could be used for business analysis. It invokes a multiple linear regression application built using the UTLNLA package. The multiple regression application is implemented in an object called OLSRegression. Note that sample files for the OLS Regression object can be found in ORACLEHOMEplsqldemo . Consider the scenario of a retailer analyzing the effectiveness of its marketing program. Each of its stores allocates its marketing budget over the following possible programs: media advertisements ( media ), promotions ( promo ), discount coupons ( disct ), and direct mailers ( dmail ). The regression analysis builds a linear relationship between the amount of sales that an average store has in a given year ( sales ) and the spending on the four components of the marketing program. Suppose that the marketing data is stored in the following table: Then you can build the following sales-marketing linear model using coefficients: This model can be implemented as the following view, which refers to the OLS regression object: Using this view, a marketing program manager can perform an analysis such as Is this sales-marketing model reasonable for year 2004 data That is, is the multiple-correlation greater than some acceptable value, say, 0.9 The SQL for such a query might be as follows: You could also solve questions such as What is the expected base-line sales revenue of a store without any marketing programs in 2003 or Which component of the marketing program was the most effective in 2004 That is, a dollar increase in which program produced the greatest expected increase in sales See Oracle Database PLSQL Packages and Types Reference for further information regarding the use of the UTLNLA package and linear algebra. CASE Expressions Oracle now supports simple and searched CASE statements. CASE statements are similar in purpose to the DECODE statement, but they offer more flexibility and logical power. They are also easier to read than traditional DECODE statements, and offer better performance as well. They are commonly used when breaking categories into buckets like age (for example, 20-29, 30-39, and so on). The syntax for simple CASE statements is: Simple CASE expressions test if the expr value equals the comparisonexpr . The syntax for searched CASE statements is: You can use any kind of condition in a searched CASE expression, not just an equality test. You can specify only 65,535 arguments and each WHEN. THEN pair counts as two arguments. To avoid exceeding this limit, you can nest CASE expressions so that the returnexpr itself is a CASE expression. Example 22-26 CASE Suppose you wanted to find the average salary of all employees in the company. If an employees salary is less than 2000, you want the query to use 2000 instead. Without a CASE statement, you might choose to write this query as follows: Note that this runs against the hr sample schema. In this, foo is a function that returns its input if the input is greater than 2000, and returns 2000 otherwise. The query has performance implications because it needs to invoke a function for each row. Writing custom functions can also add to the development load. Using CASE expressions in the database without PLSQL, this query can be rewritten as: Using a CASE expression lets you avoid developing custom functions and can also perform faster. Example 22-27 CASE for Aggregating Independent Subsets Using CASE inside aggregate functions is a convenient way to perform aggregates on multiple subsets of data when a plain GROUP BY will not suffice. For instance, the preceding example could have included multiple AVG columns in its SELECT list, each with its own CASE expression. We might have had a query find the average salary for all employees in the salary ranges 0-2000 and 2000-5000. It would look like: Although this query places the aggregates of independent subsets data into separate columns, by adding a CASE expression to the GROUP BY clause we can display the aggregates as the rows of a single column. The next section shows the flexibility of this approach with two approaches to creating histograms with CASE . Creating Histograms You can use the CASE statement when you want to obtain histograms with user-defined buckets (both in number of buckets and width of each bucket). The following are two examples of histograms created with CASE statements. In the first example, the histogram totals are shown in multiple columns and a single row is returned. In the second example, the histogram is shown with a label column and a single column for totals, and multiple rows are returned. Example 22-28 Histogram Example 1 Example 22-29 Histogram Example 2 Frequent Itemsets Instead of counting how often a given event occurs (for example, how often someone has purchased milk at the grocery), you may find it useful to count how often multiple events occur together (for example, how often someone has purchased both milk and cereal together at the grocery store). You can count these multiple events using what is called a frequent itemset, which is, as the name implies, a set of items. Some examples of itemsets could be all of the products that a given customer purchased in a single trip to the grocery store (commonly called a market basket), the web pages that a user accessed in a single session, or the financial services that a given customer utilizes. The practical motivation for using a frequent itemset is to find those itemsets that occur most often. If you analyze a grocery stores point-of-sale data, you might, for example, discover that milk and bananas are the most commonly bought pair of items. Frequent itemsets have thus been used in business intelligence environments for many years, with the most common one being for market basket analysis in the retail industry. Frequent itemset calculations are integrated with the database, operating on top of relational tables and accessed through SQL. This integration provides the following key benefits: Applications that previously relied on frequent itemset operations now benefit from significantly improved performance as well as simpler implementation. SQL-based applications that did not previously use frequent itemsets can now be easily extended to take advantage of this functionality. Frequent itemsets analysis is performed with the PLSQL package DBMSFREQUENTITEMSETS. See Oracle Database PLSQL Packages and Types Reference for more information. In addition, there is an example of frequent itemset usage in Frequent itemsets . Scripting on this page enhances content navigation, but does not change the content in any way.

No comments:

Post a Comment