0

我有以下问题:

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

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

我想在同一日期获得两张桌子的总数......

4

2 回答 2

1

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

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)).

于 2012-05-23T10:13:53.250 回答
1

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

消息 8120,级别 16,状态 1,第 4 行列“employeesales.dateSold”在选择列表中无效,因为它既不包含在聚合函数或 GROUP BY 子句中。

我稍微变了,

用这个

select dt , sum(sales) from ( select dateSold as dt , sum(Price * Qty) as sales from employeesales group by dateSold union all select dateSold , sum(Price * qty) from customerboughtitems group by dateSold ) as SubQueryAlias group by dt

于 2012-05-23T10:30:46.370 回答