I don't have access to Access (pardon the pun! :-) ), but this should get you pretty close to what you want (see fiddle here):
Create and populate a party
table (could also be called entity):
CREATE TABLE party (party_id SERIAL NOT NULL PRIMARY KEY, party_name VARCHAR (25));
INSERT INTO party (party_name) VALUES ('Bill'), ('Fred'), ('Mary'), ('Jim');
Then do the same for a trxn
table (don't want to call a table "transaction" - SQL keyword!) So:
CREATE TABLE trxn
(
t_id SERIAL NOT NULL PRIMARY KEY,
party_1 INT NOT NULL,
party_2 INT NOT NULL,
item VARCHAR (25) NOT NULL,
t_amount INT NOT NULL CHECK (t_amount > 0),
CONSTRAINT ck_parties_different CHECK (party_1 != party_2),
CONSTRAINT fk_trxn_party_1 FOREIGN KEY (party_1) REFERENCES party (party_id),
CONSTRAINT fk_trxn_party_2 FOREIGN KEY (party_2) REFERENCES party (party_id)
);
and populate it:
INSERT INTO trxn (party_1, party_2, item, t_amount) VALUES (1, 2, 'Car', 45);
INSERT INTO trxn (party_1, party_2, item, t_amount) VALUES (2, 3, 'Car', 50);
INSERT INTO trxn (party_1, party_2, item, t_amount) VALUES (2, 4, 'Ship', 450);
INSERT INTO trxn (party_1, party_2, item, t_amount) VALUES (4, 1, 'Ship', 500);
INSERT INTO trxn (party_1, party_2, item, t_amount) VALUES (3, 2, 'Book', 5);
INSERT INTO trxn (party_1, party_2, item, t_amount) VALUES (2, 4, 'Book', 7);
INSERT INTO trxn (party_1, party_2, item, t_amount) VALUES (3, 1, 'TV', 60);
INSERT INTO trxn (party_1, party_2, item, t_amount) VALUES (1, 2, 'TV', 70);
Obviously, party_1
could be called seller
and party_2
the buyer
, but I tried to stick to the vocabulary you used in the question.
Then run the following SQL:
SELECT
t.t_id, p1.party_id, p1.party_name, ' sold to ' AS Action , p2.party_name,
' a ' AS what, t.item, t.t_amount
FROM party p1
JOIN trxn t
ON p1.party_id = t.party_1
JOIN party p2
ON t.party_2 = p2.party_id
ORDER BY t.t_id;
Result:
t_id party_id party_name action party_name a item t_amount
1 1 Bill sold to Fred a Car 45
2 2 Fred sold to Mary a Car 50
3 2 Fred sold to Jim a Ship 450
4 4 Jim sold to Bill a Ship 500
5 3 Mary sold to Fred a Book 5
6 2 Fred sold to Jim a Book 7
7 3 Mary sold to Bill a TV 60
8 1 Bill sold to Fred a TV 70
I hope this helps you with your problem. You should probably read up a bit about SQL and in particular about JOIN
ing tables - and especially about using the same table twice within a query which is what you need here - you have to include the party
table twice because there is both seller and buyer - (party_1 and party_2). If this is not what you require, leave a comment with @Vérace in the text and I'll see it come up in my inbox. p.s. welcome to the forum! :-)
p.p.s. Almost forgot to mention that if can have multiple transactions between the same seller and buyer, you will have to put a timestamp on your transactions and JOIN
using that as well!