-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathqueries.sql
More file actions
90 lines (79 loc) · 2.2 KB
/
queries.sql
File metadata and controls
90 lines (79 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* Количество книг */
SELECT COUNT(*)
FROM books;
/* Упорядочить результат */
SELECT
authors.lastname,
count(authors.lastname)
FROM authors
GROUP BY authors.lastname
ORDER BY count(authors.lastname) DESC;
/* Пример с HAVING */
SELECT
authors.lastname,
count(authors.lastname)
FROM authors
GROUP BY
authors.lastname
HAVING count(authors.lastname) > 1
ORDER BY count(authors.lastname) DESC;
/* Информация о книгах */
SELECT
authors.firstname AS "Имя",
authors.lastname AS "Фамилия",
books.title AS "Название",
books.release_date AS "Год выхода",
books.page_count AS "Страниц"
FROM books
INNER JOIN authors
ON books.author_id = authors.id;
/* Информация о книга + страна */
SELECT
authors.firstname AS "Имя",
authors.lastname AS "Фамилия",
books.title AS "Название",
books.release_date AS "Год выхода",
books.page_count AS "Страниц",
countries.title AS "Страна"
FROM books
INNER JOIN authors
ON books.author_id = authors.id
LEFT JOIN countries
ON books.country_id = countries.id;
/* Авторы и количество книг */
SELECT
authors.firstname AS "Имя",
authors.lastname AS "Фамилия",
COUNT(books.id) AS "Кол-во книг"
FROM
authors
INNER JOIN books
ON authors.id = books.author_id
GROUP BY
authors.firstname,
authors.lastname;
/* Автор + количество книг + упорядочивание */
SELECT
authors.firstname AS "Имя",
authors.lastname AS "Фамилия",
COUNT(books.id) AS "Кол-во книг"
FROM
authors
INNER JOIN books
ON authors.id = books.author_id
GROUP BY
authors.firstname,
authors.lastname
ORDER BY
COUNT(books.id) DESC;
/* Функции для работы со строками */
SELECT
concat(authors.firstname, ' ', authors.lastname) AS "Автор",
concat(authors.lastname, ' ', left(authors.firstname, 1)) AS "Автор2",
md5(authors.lastname) AS "hash"
FROM authors
/* Форматирование года */
SELECT
concat(authors.firstname, ' ', authors.lastname) AS "Автор",
to_char(authors.birth_date, 'YYYY') "Год рождения"
FROM authors