Scottish Parliament/zh

From SQLZoo

蘇格蘭議會

這些數據包括蘇格蘭議會1999年的全部成員。大部份成員都屬於政黨。有些政黨的領導人在議會中。有兩個表格:

msp蘇格蘭議會
Name名字 Party政黨 Constituency選區
Adam MSP, BrianSNPNorth East Scotland
Aitken MSP, BillConGlasgow
Alexander MSP, Ms WendyLabPaisley North
...記錄總數: 129
party政黨
Code代碼 Name政黨名 Leader領導人
ConConservativeMcLetchie MSP, David
GreenGreen
LabLabourDewar MSP, Rt Hon Donald
... 記錄總數: 9

選擇 NULL 值

處理NULL

一個成員被工黨逐出黨,現沒屬任何黨。找出他。

You might think that the phrase dept=NULL would work here. It doesn't. This is because NULL "propogates". Any normal expression that includes NULL is itself NULL, thus the value of the expressions 2+NULL and party || NULL and NULL=NULL for example are all NULL.

The NULL value does not cause a type error, however it does infect everything it touches with NULL-ness. We call this element the bottom value for the algebra - but we don't snigger because we are grown-ups. Bottom Type.

SELECT name FROM msp WHERE party IS NULL

列出每個黨及其領導人。

SELECT name, leader FROM party

列出每個黨及其領導人,這些黨其實是沒有領導人的。

SELECT name, leader FROM party
  WHERE leader IS NOT NULL

列出政黨名單,當中最少有一名黨員在議會內。

SELECT DISTINCT party.name FROM msp, party
  WHERE party=code

Outer joins

列出議會成員的名單,如有所屬政黨,一同列出。確保 Canavan MSP, Dennis 是在名單中。 按msp.name順序排列。

SELECT msp.name, party.name
  FROM msp LEFT JOIN party ON party=code
  ORDER BY msp.name


列出議會中每一政黨的黨員人數。

SELECT party.name, COUNT(msp.name)
  FROM msp, party
  WHERE msp.party=party.code
  GROUP BY party.name

列出每一政黨的議會中黨員人數,包括沒有黨員在議會中的政黨。

SELECT party.name, COUNT(msp.name)
  FROM party 
  LEFT JOIN msp ON party.code=msp.party
  GROUP BY party.name

Self joins are the topic for the next tutorial

Note

Sadly Donald Dewar died in 2000. An able and popular leader of the Labour Party in Scotland.