MSSQL表1和表2中日期的总和

时间:2012-05-23 09:23:36

标签: sql-server sum subquery

我遇到以下问题:

我有两个表1表用于客户购买的物品,另一表用于员工销售:

Table 1 (Emp)
EmpId 
ProductId
dateSold
Price
Qty

Table 2 (Cust)
CustomerId
ProductId
dateSold
Price
Qty

这是目前正在进行的查询:

SELECT  SUM(EmployeeSales.productPrice * EmployeeSales.Qty + 
            userBoughtItems.ProductPrice * userBoughtItems.qty) AS Total, 
        EmployeeSales.dateSold, 
        userBoughtItems.dateSold AS Expr1
FROM    EmployeeSales 
INNER JOIN userBoughtItems ON EmployeeSales.dateSold = userBoughtItems.dateSold
GROUP BY EmployeeSales.dateSold, userBoughtItems.dateSold

我想在同一天获得两个表的总数......

2 个答案:

答案 0 :(得分:1)

join为左表中的每个匹配行重复右表。在您的示例中,我希望会导致大量重复行。请考虑使用union代替:

select  cast(dt as date)
,       sum(sales)
from    (
        select  dateSold as dt
        ,       productPrice * Qty as sales
        from    EmployeeSales
        union all
        select  dateSold
        ,       ProductPrice * qty
        from    userBoughtItems
        ) as SubQueryAlias
group by
        cast(dt as date)

子查询包含所有销售的列表,外部查询每天汇总它们。

如果您使用的是SQL Sever 2005或更早版本,请将cast(dt as date)替换为dateadd(dd, 0, datediff(dd, 0, dt))

答案 1 :(得分:1)

如果没有group by子句,它就无法正常工作,会引发以下错误。

  

消息8120,级别16,状态1,行4列'employeesales.dateSold'是   在选择列表中无效,因为它不包含在任何一个中   聚合函数或GROUP BY子句。

我稍微改变了,

使用此

  

选择dt,sum(sales)from(           选择dateSold作为dt           ,总和(价格*数量)作为销售           来自employeesales group by dateSold           联合所有           选择dateSold           ,总和(价格*数量)           来自customerboughtitems group by dateSold           )作为SubQueryAlias group by           DT