当一个表没有行时,如何对不同表中的总计求和

时间:2012-09-18 19:48:50

标签: sql-server-2008-r2

我试图将table1中两列的结果相互减去,如果该表中存在数据,则从table2中添加总数。并不总是会有table2中的数据,所以如果没有任何内容,我需要使用“0”。到目前为止,这是我在表2中有数据时返回错误数量的内容。

SELECT 
    CONVERT(CHAR(10),table1.PostingDate, 120) AS business_date, 
    table1.Location AS store_number, 
    (CASE WHEN COUNT(table2.Document) > 0 THEN 
          SUM(table1.Total - table1.TipAmount + table2.Total)
          Else 
                SUM(table1.Total-table1.TipAmount) 
    END) AS net_sales_ttl
FROM table1 
    left join table2 
        on CONVERT(CHAR(10),table1.PostingDate, 120) = CONVERT(CHAR(10),table2.PostingDate, 120)
WHERE table1.PostingDate between '2012-09-09' and '2012-09-16'
GROUP BY CONVERT(CHAR(10),table1.PostingDate, 120), table1.Location

结果如下:

business_date   store_number    net_sales_ttl
2012-09-09  xxx         1699.61
2012-09-10  xxx             923.56
2012-09-11  xxx             1230.93  <--This should be 1399.93
2012-09-12  xxx             874.98
2012-09-13  xxx             1342.21
2012-09-14  xxx             1609.6
2012-09-15  xxx             2324.31

由于某种原因,查询没有正确地进行数学运算并返回错误的值。 table2具有值的唯一一天是09-11-12,该数量仅为-1.00。它给了我1230.93,这是正确值的-169。我不知道-169应该在-1.00时来自哪里。 table1中的原始金额为1400.93,而table2应从-1.00中减去,结果为1399.93。

    Sample data:
    table1 has date, location, and sales
    09-09 1111 5.00
    09-10 1111 3.00
    09-11 1111 7.00
    09-12 1111 10.00
    table2 has refunds
    09-11 1111 -1.00

    Return set would look like this:
    09-09 1111 5.00
    09-10 1111 3.00
    09-11 1111 6.00   <--Reflecting the refund from table2
    09-12 1111 10.00

0 个答案:

没有答案
相关问题