1

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

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,应从 -1.00 中减去 table2,结果为 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
4

1 回答 1

0

尝试

SELECT  
    CONVERT(CHAR(10),table1.PostingDate, 120) AS business_date,  
    table1.Location AS store_number,  
    SUM (table1.Total - table1.TipAmount + isnull(table2.Total,0))
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 

此外,一些样本数据会有所帮助 - 单独的总数无济于事

根据您的示例数据,试试这个。

Select date, location, sum(sales)
from 
(
    select date, location, sales from table1 
    union
    select date, location, refunds from table2 
) v
group by date, location
于 2012-09-18T19:57:32.450 回答