Subquey nella clausola FROM

Anche se le subquery di solito si trovano nella clausola WHERE, possono essere usate anche nella clausola FROM.

Quando sono utilizzate in questo modo, occorre specificare una clausola AS per dare un nome al risultato della subquery.

Esempi

CREATE TABLE student (name CHAR(10), test CHAR(10), score TINYINT); 

INSERT INTO student VALUES 
  ('Chun', 'SQL', 75), ('Chun', 'Tuning', 73), 
  ('Esben', 'SQL', 43), ('Esben', 'Tuning', 31), 
  ('Kaolin', 'SQL', 56), ('Kaolin', 'Tuning', 88), 
  ('Tatiana', 'SQL', 87), ('Tatiana', 'Tuning', 83);

Supponiamo di voler ottenere le medie dei singoli studenti. In altre parole, la media di Chun è 148 (75+73), quella di Esben è 74 (43+31), etc.

Non è possibile fare quanto segue:

SELECT AVG(SUM(score)) FROM student GROUP BY name;
ERROR 1111 (HY000): Invalid use of group function

Invece le subquery nella FROM sono permesse:

SELECT AVG(sq_sum) FROM (SELECT SUM(score) AS sq_sum FROM student GROUP BY name) AS t;
+-------------+
| AVG(sq_sum) |
+-------------+
|    134.0000 |
+-------------+

Commenti

Sto caricando i commenti......
Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.