Janoš Vidali
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- tags: vaje, opb, create, group, order hackmd: https://hackmd.io/i2JTLX9bR7GYY5NUZLwPtw --- # Osnove podatkovnih baz - vaje 24.2.2022 --- ## `CREATE TABLE` (ključi, omejitve), `ORDER BY`, `GROUP BY` ```sql CREATE TABLE tabela ( st1 tip [PRIMARY KEY] [UNIQUE] [NOT NULL] [CHECK (pogoj)] [DEFAULT vrednost] [REFERENCES tabela(stolpec)], st2 tip ..., ..., [PRIMARY KEY (st1, st2, ...),] [UNIQUE (st1, st2, ...),] [CHECK (pogoj),] [FOREIGN KEY (st1, st2, ...) REFERENCES tabela(st1, st2, ...)] ); ``` --- ### Naloga 1: `CREATE TABLE` Naredi sledeče tabele, v katerih boš hranil podatke o osebah, njihovih traktorjih in rezervnih delih za traktorje: ``` oseba(id, ime, rojstvo) otroci(stars, otrok) znamka(id, ime) traktor(id, lastnik, znamka, barva, nakup) deli(lastnik, znamka, tip, stevilo) ``` * Tabela `oseba` opisuje posamezne osebe. * Tabela `otroci` vsebuje IDje vseh staršev in njihovih otrok. * Tabela `znamka` našteva znamke traktorjev. ID znamke naj bo serijska številka, ki se določi avtomatično (pri vpisu vrstice nam je ni treba posebej navajati). * Tabela `traktor` opisuje posamezne traktorje. Barva traktorja je lahko neznana (`NULL`). Če čas nakupa pri vstavljanju v bazo ni podan, privzemi, da je bil traktor kupljen v trenutku vnosa vrstice v bazo. Uporabi funkcijo `now()`, ki vrne trenutni čas. ID traktorja naj bo serijska številka, ki se določi avtomatično. * Tabela `deli` opisuje nadomestne dele. Posamezna vrstica opisuje enega ali več (stolpec `stevilo`) nadomestnih delov določenega tipa (npr. volan) za traktor določene znamke. Če število delov pri vnosu v tabelo ni podano, privzemi, da je del en sam. Preden narediš tabele, si dobro oglej datoteko [`kmetija_insert.sql`](https://ucilnica.fmf.uni-lj.si/pluginfile.php/16308/mod_page/intro/kmetija_insert.sql), s katero boš tabele pozneje napolnil; na podlagi te datoteke tudi določi smiselne podatkovne tipe, primarne in tuje ključe ter omejitve. Tabele naredi tako, da se bodo ob vstavljanju prožile napake natanko na tistih mestih, kjer je to označeno v `kmetija_insert.sql`. Če se pri ustvarjanju tabel zmotiš, jih lahko bodisi uničiš z ukazom `DROP TABLE` in začneš znova, bodisi poskusiš popraviti z ukazom [`ALTER TABLE`](http://www.postgresql.org/docs/current/static/sql-altertable.html). ```sql CREATE TABLE oseba ( id INTEGER PRIMARY KEY, ime TEXT NOT NULL, rojstvo DATE NOT NULL ); CREATE TABLE otroci ( stars INTEGER REFERENCES oseba(id), otrok INTEGER REFERENCES oseba(id), PRIMARY KEY (stars, otrok), CHECK (stars <> otrok) ); CREATE TABLE znamka ( id SERIAL PRIMARY KEY, ime TEXT NOT NULL UNIQUE ); CREATE TABLE traktor ( id SERIAL PRIMARY KEY, lastnik INTEGER NOT NULL REFERENCES oseba(id), znamka INTEGER NOT NULL REFERENCES znamka(id) , barva TEXT, nakup DATE NOT NULL DEFAULT now() CHECK (nakup <= now()) ); CREATE TABLE deli ( lastnik INTEGER NOT NULL REFERENCES oseba(id), znamka INTEGER NOT NULL REFERENCES znamka(id), tip TEXT NOT NULL, stevilo INTEGER NOT NULL DEFAULT 1 CHECK (stevilo > 0) -- PRIMARY KEY (lastnik, znamka, tip) ); ``` --- ### Naloga 2: Določili `ORDER BY`, `LIMIT` ```sql SELECT [DISTINCT] st1, st2, ... FROM tabela WHERE pogoj ORDER BY st1 [ASC | DESC], st2 [ASC | DESC] LIMIT stevilo [OFFSET stevilo]; ``` Pogosto želimo prikazati rezultate poizvedbe v določenem vrstnem redu. V ta namen uporabimo določilo `ORDER BY` (glej [dokumentacijo za `ORDER BY`](http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-ORDERBY) za Postgresql in [članek `ORDER BY` (SQL)](http://wiki.fmf.uni-lj.si/wiki/ORDER_BY_%28SQL%29) iz MaFiRa wiki). V podatkovni zbirki `banka` napravi naslednje poizvedbe: 1. seznam vseh krajev, urejen po imenu kraja (ali baza pravilno uredi šumnike?) ```sql SELECT kraj FROM kraj ORDER BY kraj; ``` 2. seznam vseh oseb, urejen v padajočem vrstnem redu po datumu rojstva ```sql SELECT * FROM oseba ORDER BY rojstvo DESC; ``` V praksi imamo podatkov dostikrat zelo veliko in zato ni smiselno, da bi izpisovali vse. Takrat uporabimo [`LIMIT`](http://www.postgresql.org/docs/current/static/queries-limit.html): 1. Izpiši najmlajšega komitenta banke. ```sql SELECT oseba.* FROM oseba JOIN racun ON racun.lastnik = oseba.emso ORDER BY rojstvo DESC LIMIT 1; ``` 2. Izpiši tiste tri transakcije, pri katerih se je obrnilo največ denarja. ```sql SELECT * FROM transakcija ORDER BY abs(znesek) DESC LIMIT 3; ``` ### Naloga 3: Določilo `GROUP BY` ```sql SELECT count(*) FROM tabela WHERE pogoj GROUP BY st1, st2, ...; ``` Z določilom `GROUP BY` rezultate poizvedbe združimo v posamezne skupine, vsako skupino pa združimo v eno vrstico z agregacijsko funkcijo, kot je `sum` ali `count` (glej [dokumentacijo za `GROUP BY`](http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-GROUPBY) za PostgreSQL in [članek `GROUP BY` (SQL)](http://wiki.fmf.uni-lj.si/wiki/GROUP_BY_%28SQL%29) iz MaFiRa wiki). V podatkovni zbirki `banka` napravi naslednje poizvedbe: 1. število oseb, ki živijo v vsakem posameznem kraju. Izpiši dva stolpca: poštna številka in število naročnikov, ki živijo v kraju s to poštno številko. ```sql SELECT posta, count(*) AS stevilo FROM oseba GROUP BY posta; ``` 2. trenutno stanje na računih oseb (brez obresti). Izpiši dva stolpca: številka računa in trenutno stanje. ```sql SELECT racun, sum(znesek) FROM transakcija GROUP BY racun; ``` 3. trenutno stanje na računih oseb (brez obresti). Izpiši štiri stolpce: številka računa, ime, priimek lastnika in trenutno stanje. ```sql SELECT oseba.ime, oseba.priimek, racun, sum(znesek) AS stanje FROM transakcija JOIN racun ON racun.stevilka = transakcija.racun JOIN oseba ON racun.lastnik = oseba.emso GROUP BY oseba.ime, oseba.priimek, racun.lastnik, transakcija.racun; ``` Določili `ORDER BY` in `GROUP BY` lahko uporabimo hkrati: 1. izpiši trenutno stanje na računih naročnikov (brez obresti). Izpiši štiri stolpce: številka računa, ime, priimek, trenutno stanje. Izpis naj bo urejen po trenutnem stanju v padajočem vrstnem redu. ```sql SELECT oseba.ime, oseba.priimek, racun, sum(znesek) AS stanje FROM transakcija JOIN racun ON racun.stevilka = transakcija.racun JOIN oseba ON racun.lastnik = oseba.emso GROUP BY oseba.ime, oseba.priimek, racun.lastnik, transakcija.racun ORDER BY sum(znesek) DESC; ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully