Sobes.tech
Middle+

Modeliuoti paprastą banko sistemą: - `accounts` lentelė: - `id`, - `owner_id`, - `currency`, - `created_at`. - `transactions` lentelė: - `id`, - `account_id`, - `amount`, - `created_at`. **Reikalavimai:** 1. Parašykite SQL, kuris sukurs schemą su būtinomis apribojimais (NOT NULL, FK, CHECK `amount` ne nulis). 2. Parašykite užklausą: - gauti dabartinį sąskaitos balansą pagal `account_id` (suma `amount`). 3. Papildomas sudėtingumas: palaikyti debetą/kreditą (dvigubas įrašas). Valymas

sobes.tech AI

Atsakymas iš AI

sql -- 1. Создание схемы с ограничениями CREATE TABLE accounts ( id SERIAL PRIMARY KEY, owner_id INT NOT NULL, currency VARCHAR(3) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW() );

CREATE TABLE transactions ( id SERIAL PRIMARY KEY, account_id INT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, amount NUMERIC NOT NULL CHECK (amount <> 0), created_at TIMESTAMP NOT NULL DEFAULT NOW() );

-- 2. Запрос для получения текущего баланса по account_id SELECT account_id, SUM(amount) AS balance FROM transactions WHERE account_id = $1 GROUP BY account_id;

-- 3. Усложнение: поддержка дебет/кредит (двойная запись) -- Для двойной записи добавим таблицу ledger_entries CREATE TABLE ledger_entries ( id SERIAL PRIMARY KEY, transaction_id INT NOT NULL REFERENCES transactions(id) ON DELETE CASCADE, account_id INT NOT NULL REFERENCES accounts(id), amount NUMERIC NOT NULL CHECK (amount <> 0), created_at TIMESTAMP NOT NULL DEFAULT NOW() );

-- В этом случае каждая транзакция будет иметь две записи в ledger_entries: -- дебет (откуда списывается) с отрицательным amount -- кредит (куда зачисляется) с положительным amount

-- Запрос баланса по account_id с учетом ledger_entries SELECT account_id, SUM(amount) AS balance FROM ledger_entries WHERE account_id = $1 GROUP BY account_id;