Query to select cards and transactions
-
12-03-2021 - |
Вопрос
I have some trouble with a query definition. My database is about operations in a bank and I want to show the card numbers which were used in transactions at all ATMs.
This is how my tables DDL:
CREATE TABLE Cards(
card_id INT PRIMARY KEY IDENTITY(1,1),
number VARCHAR(25),
CVV CHAR(3),
bankAccount_id INT REFERENCES BankAccount(account_id)
);
CREATE TABLE Transactions(
transaction_id INT PRIMARY KEY IDENTITY(1,1),
ATM_id INT REFERENCES ATM(id),
card_number INT REFERENCES Cards(card_id),
sum_money INT,
transaction_time DATETIME
);
And I tried below query:
SELECT *
FROM Cards C
WHERE C.card_id = ALL (SELECT *
FROM Transactions T
WHERE T.card_number = C.card_id
)
And it doesn't work since I used card_id on both sides. Can somebody help me, please?
Решение
You can do something like this:
SELECT T.card_number
FROM Cards AS C
INNER JOIN Transactions AS T
ON C.card_id = T.card_number
GROUP BY T.card_number -- Grouping up on Card_Number to get the count of unique ATMs each card was used at in the HAVING clause
HAVING COUNT(DISTINCT ATM_id) = (SELECT COUNT(1) FROM ATM) -- Count of distinct ATMs each card was used at needs to equal the total number of ATMs
Не связан с dba.stackexchange