SQL Server:对两列求和

时间:2018-06-22 14:59:30

标签: sql-server tsql

我有以下SQL语句,向我显示了来自销售点系统的交易。我想计算(MoneyIn-MoneyOut)列的总和,但超出了我一点,将其显示为单个值。我相信这是一个简单的mod。

  DECLARE @StartDate DateTime;
宣告@EndDate DateTime;
声明@SearchTerm NVARCHAR(200);

SET @SearchTerm ='%widget1%'
SET @StartDate ='2018-05-01 00:00:00'
SET @EndDate = DATEADD(月,1,@StartDate)

选择顶部(500)
    t.TransactionDate,
    t.MoneyIn,
    t.MoneyOut,
    t。说明,
    p.PaymentMethodName,
    t.TransactionRef,
    c.SalesItems,
    发生COUNT(*)次
从
    交易额
左联接
    耕种tl ON t.TillId = tl.TillId
内部联接
    PaymentMethods p ON t.PaymentMethodId = p.PaymentMethodsID
内部联接
    成员资格m ON t.UserId = m.UserId
交叉申请
    (选择
         STUFF((SELECT','+ CAST(tp。描述为VARCHAR(100))
                从TransactionsPosLines tp
                在哪里t.TransactionId = tp.TransactionId
                FOR XML PATH('')),1,1,'')AS SalesItems)c
哪里
    t.TransactionDate> = @StartDate
    AND t.TransactionDate <= @EndDate
    AND(t.PaymentTypeId = 1)
    AND SalesItems喜欢@SearchTerm
通过...分组
    t.TransactionDate,
    t.MoneyIn,
    t.MoneyOut,
    t。说明,
    p.PaymentMethodName,
    t.TransactionRef,
    m。用户名,
    c.SalesItems
订购
    COUNT(*)DESC
 

输出:

  2018-05-01 17:23:23.243 9.99 0.00促销-卡卡商店促销Grab n Go物品1
2018-05-08 13:15:04.577 10.00 -0.01出售-现金总计:9.99现金商店出售Grab n Go项目1
2018-05-10 14:08:47.120 7.99 0.00特价-卡卡商店出售Grab n Go物品,折扣1
 

我想展示:

总销售量:27.97

(总金额-总金额)

1 个答案:

答案 0 :(得分:0)

这样这个问题才有答案

(编辑:添加了我用来解决该问题的实际SQL,它给出了我一直在寻找的唯一结果),感谢帮助:

Select top (10000)
    sum(t.MoneyIn) - sum(t.MoneyOut) as 'moneytotal'
From
    Transactions t
    LEFT JOIN  Tills tl
    ON t.TillId = tl.TillId
    INNER JOIN PaymentMethods p
    ON t.PaymentMethodId = p.PaymentMethodsID
    INNER JOIN Membership m
    On t.UserId = m.UserId
    CROSS APPLY
    (SELECT STUFF(
        (SELECT ',' + CAST(tp.Description AS VARCHAR(100))
        FROM
        TransactionsPosLines tp
        WHERE t.TransactionId = tp.TransactionId
        FOR XML PATH(''))
        ,1,1,'') as SalesItems) c
Where
    t.TransactionDate >= @StartDate
    AND t.TransactionDate <= @EndDate
        AND (t.PaymentTypeId = 1)
        and SalesItems LIKE @SearchTerm

        Order By
  count(*) Desc

  GO