SQL Server总和基于类型

时间:2018-06-06 02:00:25

标签: sql sql-server

标题

printEvaluation(e,logs):

    print("evaluation for epoch: " + str(e))
    print(model.evaluate(x_train,y_train))

callback = LambdaCallback(on_epoch_end= printEvaluation)
callbacks = [callback]

model.fit(........, callbacks = callbacks)

type列的含义是: D + C- =借方 - 贷方 C + D- =信用 - 借记

交易:

Title        Type
Sample1      D+C-
Sample2      D+C-
Sample3      C+D-
Sample4      C+D-

我可以对每个标题求和,但我无法根据标题的类型进行计算

Type       Title       Amt
Debit      Sample1     200
Credit     Sample2     120
Debit      Sample1     110
Debit      Sample2     130
Credit     Sample3     150
Debit      Sample2     210
Debit      Sample3     250
Credit     Sample1     300
Credit     Sample4     220
编辑:我发现另一个场景,如果只有一个信用交易,谢谢

结果必须是:

SELECT
    title,
    SUM(amt) as amt
    type
FROM
    tbltran
GROUP BY
    title, type;

1 个答案:

答案 0 :(得分:2)

这个问题并不完全清楚但我会假设您要返回titleamt,其中amt是标题的总和,需要注意的是根据“标题”表中的“类型”字段,借方和贷方为负数或正数。

鉴于您的评论只有两种类型(D+C-C+D-),我们不必动态解析查询,而只需使用一些简单的CASE逻辑

以下是两个选项,其中任何一个都应该可以使用,但是我目前没有可用的SQL Server来比较它们......

QUERY 1

SELECT
    t.title,
    SUM(
      CASE WHEN t.Type = 'Credit' THEN -1 ELSE 1 END
      *
      CASE WHEN tc.Type = 'D+C-' THEN 1 ELSE -1 END
      *
      amt
    ) as amt
FROM
    tbltran t
    INNER JOIN tbltitles tc ON tc.Title = t.Title
GROUP BY
    t.title;

QUERY 2

SELECT
    t.title,
    SUM(
       CASE 
          WHEN t.Type = 'Credit' AND tc.Type = 'D+C-' THEN -amt
          WHEN t.Type = 'Credit' AND tc.Type = 'C+D-' THEN amt
          WHEN t.Type = 'Debit' AND tc.Type = 'D+C-' THEN amt
          WHEN t.Type = 'Debit' AND tc.Type = 'C+D-' THEN -amt
       END
    ) as amt
FROM
    tbltran t
    INNER JOIN tbltitles tc ON tc.Title = t.Title
GROUP BY
    t.title;

<子> <子>的 RESULT

title        amt
-----        ---
Sample1      10
Sample2      220
Sample3      -100

Query 1 SQL Fiddle

Query 2 SQL Fiddle

CASE Documentation