Modellieren Sie ein einfaches Banksystem: - Tabelle `accounts`: - `id`, - `owner_id`, - `currency`, - `created_at`. - Tabelle `transactions`: - `id`, - `account_id`, - `amount`, - `created_at`. **Anforderungen:** 1. Schreiben Sie SQL zum Erstellen des Schemas mit den erforderlichen Einschränkungen (NOT NULL, FK, CHECK auf `amount` ungleich Null). 2. Schreiben Sie eine Abfrage: - um den aktuellen Kontostand nach `account_id` (Summe von `amount`) zu erhalten. 3. Schwierigkeit: Unterstützung von Debit/Kredit (doppelte Buchung). Bereinigung.
sobes.tech KI
Antwort von AI
sql -- 1. Erstellung des Schemas CREATE TABLE konten ( id SERIAL PRIMARY KEY, owner_id INT NOT NULL, currency VARCHAR(3) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW() );
CREATE TABLE transaktionen ( id SERIAL PRIMARY KEY, account_id INT NOT NULL REFERENCES konten(id) ON DELETE CASCADE, amount NUMERIC NOT NULL CHECK (amount <> 0), created_at TIMESTAMP NOT NULL DEFAULT NOW() );
-- 2. Abfrage, um den aktuellen Kontostand nach account_id zu erhalten SELECT COALESCE(SUM(amount), 0) AS balance FROM transaktionen WHERE account_id = $1;
-- 3. Komplexität: Unterstützung für Debit/Kredit (Doppelte Buchführung) -- Es wird angenommen, dass jede Transaktion aus zwei Einträgen besteht: Debit und Kredit -- Dafür kann die Tabelle ledger_entries mit den Feldern hinzugefügt werden: CREATE TABLE ledger_entries ( id SERIAL PRIMARY KEY, transaction_id INT NOT NULL, account_id INT NOT NULL REFERENCES konten(id), amount NUMERIC NOT NULL CHECK (amount <> 0), created_at TIMESTAMP NOT NULL DEFAULT NOW(), CONSTRAINT fk_transaction FOREIGN KEY (transaction_id) REFERENCES transaktionen(id) ON DELETE CASCADE );
-- Die Tabelle transaktionen speichert jetzt allgemeine Informationen über die Überweisung (z.B. Beschreibung, Datum) -- Der Kontostand wird als Summe von amount aus ledger_entries berechnet: SELECT COALESCE(SUM(amount), 0) AS balance FROM ledger_entries WHERE account_id = $1;
"""
Auf diese Weise wird die doppelte Buchführung durch zwei Einträge in ledger_entries gewährleistet: einen mit negativem amount (Ausgabe), einen mit positivem (Eingang). Dies ist ein klassischer Ansatz in der Buchhaltung von Banksystemen.