我具有此表结构以及一些示例数据。这里的逻辑是,我针对任何COATitle
输入子记录,即针对该特定总账的支出。在我的示例数据中,Medical
具有多个子记录,并且与Incentive
相同。
我的问题是,当我选择特定的总帐户时,例如选择Medical
时,它应该显示其子记录,在这种情况下,它们不应该包含MasterID
2的记录,就像{{1 }}
Incentive
查询示例:
CREATE TABLE TransactionMaster
(
ID Int,
TransactionCode VARCHAR(25),
PRIMARY KEY (ID)
)
INSERT INTO TransactionMaster VALUES (1, 'TRA-001');
INSERT INTO TransactionMaster VALUES (2, 'TRA-002');
INSERT INTO TransactionMaster VALUES (3, 'TRA-003');
CREATE TABLE TransactionDetail
(
ID Int,
MasterID Int,
COATitle VARCHAR(25),
CrAmount NUMERIC(18,2),
DrAmount NUMERIC(18,2),
PRIMARY KEY (ID),
FOREIGN KEY (MasterID) REFERENCES TransactionMaster(ID)
)
INSERT INTO TransactionDetail VALUES (1, 1, 'Medical', '2500', NULL)
INSERT INTO TransactionDetail VALUES (2, 1, 'Travelling', NULL, '2500')
INSERT INTO TransactionDetail VALUES (3, 1, 'Medicine', NULL, '2500')
INSERT INTO TransactionDetail VALUES (4, 1, 'Doc Fee', NULL, '2500')
INSERT INTO TransactionDetail VALUES (5, 2, 'Incentive', '3000', NULL)
INSERT INTO TransactionDetail VALUES (6, 2, 'Extra', NULL, '2500')
INSERT INTO TransactionDetail VALUES (7, 2, 'Bonus', NULL, '500')
INSERT INTO TransactionDetail VALUES (8, 3, 'Medical', NULL, '3000')
INSERT INTO TransactionDetail VALUES (9, 3, 'Tests', '2500', NULL)
INSERT INTO TransactionDetail VALUES (10, 3, 'Juice', '500', NULL)
输出:
SELECT [Voucher].[TransactionCode], [Detail].[COATitle], [Detail].[CrAmount], [Detail].[DrAmount]
FROM [TransactionMaster] [Voucher], [TransactionDetail] [Detail]
WHERE [Voucher].[ID] = [Detail].[MasterID] AND COATitle NOT IN ('Medical')
所需的输出不应包含TransactionCode COATitle CrAmount DrAmount
------------------------- ------------------------- --------------------------------------- ---------------------------------------
TRA-001 Travelling NULL 2500.00
TRA-001 Medicine NULL 2500.00
TRA-001 Doc Fee NULL 2500.00
TRA-002 Incentive 3000.00 NULL
TRA-002 Extra NULL 2500.00
TRA-002 Bonus NULL 500.00
TRA-003 Tests 2500.00 NULL
TRA-003 Juice 500.00 NULL
和TransactionCode
的行。
答案 0 :(得分:2)
尝试以下查询
SELECT
m.TransactionCode,
d.COATitle,
d.CrAmount,
d.DrAmount
FROM TransactionDetail d
JOIN TransactionMaster m ON d.MasterID=m.ID
WHERE d.MasterID IN(
SELECT MasterID
FROM TransactionDetail
WHERE COATitle='Medical'
)
AND d.COATitle<>'Medical'