Sql View根据另一列计算列

时间:2015-04-21 04:06:38

标签: sql database

我有这样的数据库视图:

SELECT e.ExportID, e.Date, SUM(t.Amount) AS TotalAmount
FROM dbo.Exports AS e LEFT OUTER JOIN
dbo.Transactions AS t ON e.TransID = t.TransID
GROUP BY e.ExportID, e.Date, t.Credit

正常工作,返回值。

我需要的是在事务的foreach行中,检查列t.Credit是否为true,如果为true则添加到TotalAmount,如果为false则从TotalAmount中减去?

由于

2 个答案:

答案 0 :(得分:4)

假设您的t.credit数据类型为布尔值,您可以将总和更改为:

sum(case when t.credit then t.amount else -t.amount end)

答案 1 :(得分:4)

SELECT e.ExportID, e.Date, SUM(IF(t.Credit = 'true', t.Amount, -t.Amount)) AS TotalAmount
FROM dbo.Exports AS e LEFT OUTER JOIN
dbo.Transactions AS t ON e.TransID = t.TransID
GROUP BY e.ExportID, e.Date, t.Credit

由于:

SELECT IF('true' = 'true', 1, 0);
+---------------------------+
| IF('true' = 'true', 1, 0) |
+---------------------------+
|                         1 |
+---------------------------+
SELECT IF('true' = 'false', 1, 0);
+----------------------------+
| IF('true' = 'false', 1, 0) |
+----------------------------+
|                          0 |
+----------------------------+

理由:

SELECT SUM(IF(t.Credit = 'true', t.Amount, -t.Amount))
FROM (
    SELECT 1 AS Amount, 'true' AS Credit
    UNION
    SELECT 2 AS Amount, 'false' AS Credit
    UNION
    SELECT 5 AS Amount, 'true' AS Credit
) t;

结果:

+-------------------------------------------------+
| SUM(IF(t.Credit = 'true', t.Amount, -t.Amount)) |
+-------------------------------------------------+
|                                               4 |
+-------------------------------------------------+