如何返回相反的交易值行

时间:2019-03-08 05:48:49

标签: sql sql-server

我具有这种表结构,我想要一个需要返回相对侧列值的查询。

CREATE TABLE TransactionDetail
(
  ID NUMERIC NOT NULL PRIMARY KEY,
  TransactionCode bigint,
  COATitle NVARCHAR(50),
  DrAmount NUMERIC,
  CrAmount NUMERIC
);

INSERT INTO TransactionDetail VALUES (1, 1, 'Overtime', '2500', NULL);
INSERT INTO TransactionDetail VALUES (2, 1, 'Internship', NULL, '1500');
INSERT INTO TransactionDetail VALUES (3, 1, 'Medical', NULL, '1000');
INSERT INTO TransactionDetail VALUES (4, 2, 'Internship', '1150', NULL);
INSERT INTO TransactionDetail VALUES (5, 2, 'Overtime', NULL, '1150');
INSERT INTO TransactionDetail VALUES (6, 3, 'Overtime', '600', NULL);
INSERT INTO TransactionDetail VALUES (7, 3, 'Refreshment', '400', NULL);
INSERT INTO TransactionDetail VALUES (8, 3, 'Car Loan', '200', NULL);
INSERT INTO TransactionDetail VALUES (9, 3, 'Office Expenses', NULL, '1200');

如果我传递参数值为Overtime,则它应该返回以下行

SELECT COATitle, DrAmount, CrAmount
FROM TransactionDetail
WHERE COATitle <> Overtime

Internship      NULL    1500
Medical         NULL    1000
Internship      1150    NULL
Office Expenses NULL    1200

如果选择的帐户位于Debit侧,则应打印Credit侧帐户;如果选择的帐户位于Credit侧,则应打印{{ 1}}方面针对该特定Debit

1 个答案:

答案 0 :(得分:1)

以下代码给出了所需的结果。通过检查当前交易中提供的参数是借方还是贷方(或不存在)来做到这一点,然后仅显示指定的反向。

declare @Parameter nvarchar(50) = 'Overtime'

declare @Trans TABLE
(
  ID NUMERIC NOT NULL,
  TransactionCode bigint,
  COATitle NVARCHAR(50),
  DrAmount NUMERIC,
  CrAmount NUMERIC
);

INSERT INTO @Trans VALUES (1, 1, 'Overtime', '2500', NULL);
INSERT INTO @Trans VALUES (2, 1, 'Internship', NULL, '1500');
INSERT INTO @Trans VALUES (3, 1, 'Medical', NULL, '1000');
INSERT INTO @Trans VALUES (4, 2, 'Internship', '1150', NULL);
INSERT INTO @Trans VALUES (5, 2, 'Overtime', NULL, '1150');
INSERT INTO @Trans VALUES (6, 3, 'Overtime', '600', NULL);
INSERT INTO @Trans VALUES (7, 3, 'Refreshment', '400', NULL);
INSERT INTO @Trans VALUES (8, 3, 'Car Loan', '200', NULL);
INSERT INTO @Trans VALUES (9, 3, 'Office Expenses', NULL, '1200');

select TransactionCode, COATitle, DrAmount, CrAmount
from (
  SELECT TransactionCode, COATitle, DrAmount, CrAmount
    , case when exists (select 1 from @Trans T1 where T1.TransactionCode = T.TransactionCode and T1.COATitle = @Parameter and DrAmount is not null) then 1
      when exists (select 1 from @Trans T1 where T1.TransactionCode = T.TransactionCode and T1.COATitle = @Parameter and CrAmount is not null) then -1
      else 0 end TransSign
  FROM @Trans T
  WHERE COATitle <> @Parameter
) X
where (TransSign = -1 and DrAmount is not null)
or (TransSign = 1 and CrAmount is not null)