just_for_fun/code/python/db_connect/sql/select.sql
2025-05-19 13:04:38 +03:00

69 lines
1.7 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- Алиасы вычесление в столбцах, применение функций
select a.id, a.login || ' ' || a.login login, 2+2 as summ_
from account a
where ( id in (1,2) and login ilike 'BOB')
--inner join с конструкцией CASE
select a.login, p."name" || ' ' || p.surname as fio,
to_char(p.dt_birth, 'DD.MM.YYYY') dt_birth,
CASE
when p.sex THEN 'Девушка'
ELSE 'Мужчина'
END as sex, r."name"
from account a, profile p, role_account ra ,"role" r
where a.id = p.id_account
and ra.acconts = a.id
and ra.roles = r.id
-- LEFT JOIN получение при запросе пересечение с NULL строками
-- Запрос представлен в виде таблицы
select * from
( SELECT a.login login, p."name"
FROM account a
LEFT JOIN profile p ON a.id = p.id_account
WHERE p."name" is null) null_acc
where null_acc.login not like 'bob' ;
-- Создание представления в БД на базе
create view v_account as
SELECT a.login
FROM account a
where NOT EXISTS (SELECT * FROM profile p
WHERE p.id_account = a.id )
select * from v_account va;
-- Объединение запросов
union all
SELECT a.login
FROM account a
where NOT EXISTS (SELECT * FROM profile p
WHERE p.id_account = a.id )
-- Запросы с группировкой group by, having
select ra.roles, count(ra.roles)
from account a, role_account ra
where a.id = ra.acconts
group by ra.roles
having count(ra.roles) > 2