sql汇总计数并从2个表中添加金额

时间:2014-07-01 14:03:50

标签: sql

我正在使用最后一个sql。

前两个分组给了我正确的答案,但最后一个涉及加入2个表格给了我一个太高的数字,当我手动添加前两个。

sql生成图1,2和(1 + 2)生成3。

请帮助。 下面的SQL ....

select      [OrderDate]     as "Date", 
            'Cobs'          as "Payment Source", 
            COUNT(*)        as "Quantity", 
            SUM([Amount])   as "Value in Pounds"
from        cobaltins
where       PN like 'BT%'
group by    OrderDate

union all

select      [OrderDate]     as "Date", 
            'Cobs Adhoc'    as "Payment Source",
            COUNT(*)        as "Quantity", 
            SUM([Amount])   as "Value in Pounds"
FROM        cobaltins_adhoc
where       name = 'Vauz'
group by    OrderDate

union all

select      cba.OrderDate   as "Date", 
            'Cumulative'    as "Payment Source",
            COUNT(*)        as "Quantity", 
            sum((cb.Amount)+(cba.Amount)) as "Value in Pounds"
FROM        cobaltins       as cb 
left join   cobaltins_adhoc as cba  on cb.OrderDate = cba.OrderDate
where       cb.PN like 'BT%' 
    or      cba.name = 'Vauz'
group by    cba.OrderDate

4 个答案:

答案 0 :(得分:0)

您加入的方式

FROM cobaltins as cb
LEFT JOIN cobaltins_adhoc as cba
ON cb.OrderDate = cba.OrderDate

仅在订单日期加入。如果你每个日期有多个订单,那么它会尝试任意加入这些订单。你会想要在该联接中添加其他内容以使其与众不同。

答案 1 :(得分:0)

您正在加入OrderDate。

这意味着如果任一表中有多个行具有相同的订单日期,那么您将获得另一个表中匹配行的重复。

快速测试方法是删除COUNT(*)和GROUP BY,然后查看连接的结果。您是否看到任何您不想要重复的重复项?

答案 2 :(得分:0)

为什么不用列而不是行来做呢?

select bt."Date", bt.Quantity as Cobs, vauz.Quantity as CobsAdhoc,
       (bt.quantity + coalesce(vauz.Quantity)) as Total
from (select [OrderDate] as "Date", 'Cobs' as "Payment Source", COUNT(*) as "Quantity",
             SUM([Amount]) as "Value in Pounds"
      from cobaltins
      where PN like 'BT%'
      group by OrderDate
     ) bt left outer join
     (select [OrderDate] as "Date", 'Cobs Adhoc' as "Payment Source",COUNT(*) as "Quantity", 
             SUM([Amount]) as "Value in Pounds"
      FROM cobaltins_adhoc
      where name = 'Vauz'
      group by OrderDate
     ) vauz
     on bt."Date" = vauz."Date";

答案 3 :(得分:0)

您可能想尝试对UNION的内联视图求和,而不是尝试将其合并为一个

SELECT 
        "Date", 
        "Payment Source", 
         SUM(Quantity) Quantity,
         SUM("Value in Pounds") "Value in Pounds"
 FROM 
(
        select  [OrderDate] as "Date",
                  'Cobs' as "Payment Source", 
                COUNT(*) as "Quantity",
             SUM([Amount]) as "Value in Pounds"
         from cobaltins
         where PN like 'BT%'
         group by OrderDate

        union all

        select [OrderDate] as "Date", '
               Cobs Adhoc' as "Payment Source",COUNT(*) as "Quantity", 
               SUM([Amount]) as "Value in Pounds"
        FROM cobaltins_adhoc
         where name = 'Vauz'
        group by OrderDate
) t 
GROUP BY 
        "Date", 
        "Payment Source"