0

我有两张桌子。

  1. Customer ID, NAME, MonthlyIncome
  2. Orders ID, CustomerKey, TotalCost

我想把这两张桌子合二为一,就像在商店里买的总金额一样。

CustomerKey, MonthlyIncome, TotalCost.

我试图按 分组CustomerKey,但我无法包括其余的列。我应该使用哪个查询?

SELECT 
    fs.CustomerKey, SUM(fs.TotalCost) as TotalBought
FROM 
    FactOnlineSales fs
INNER JOIN 
    DimCustomer c on c.CustomerKey = fs.CustomerKey
GROUP BY 
    fs.CustomerKey
4

3 回答 3

1

我尝试按 CustomerKey 分组,但无法管理如何包含其余列。

就这样做

SELECT fs.CustomerKey,
       c.MonthlyIncome,
       SUM(fs.TotalCost) as TotalBought
  FROM FactOnlineSales fs
       INNER JOIN DimCustomer c
         ON c.CustomerKey = fs.CustomerKey
 GROUP BY fs.CustomerKey,
          c.MonthlyIncome

大概CustomerKey是唯一的,因此按不太唯一的列分组不会改变SUM总数。

于 2013-03-17T05:15:52.887 回答
1

您没有提及您使用的 SQL Server版本- 但如果您使用的是 SQL Server 2005或更高版本,则可以使用以下OVER()子句:

SELECT 
    fs.CustomerKey, 
    c.MonthlyIncome,
    TotalBought = SUM(fs.TotalCost) OVER(PARTITION BY fs.CustomerKey)
FROM 
    FactOnlineSales fs
INNER JOIN 
    DimCustomer c on c.CustomerKey = fs.CustomerKey

这基本上给了你CustomerKeyMonthlyIncome然后TotalCost对每个求和,CustomerKey并在你的输出中显示适当的值。GROUP BY在这种情况下不需要做 a

于 2013-03-17T09:28:24.027 回答
1

您可能在连接的 ON 子句中有错误。
您使用CustomerKey而不是Customer IDDimCustomer表中。对于分组:您必须按未聚合的每一列进行分组,因此您可以包括NAME(因此您可以拥有描述性客户)和 MonthlyIncome.

SELECT 
    c."Customer ID",
    c.NAME, 
    c.MonthlyIncome,
    SUM(fs.TotalCost) as TotalBought
FROM 
    FactOnlineSales fs INNER JOIN DimCustomer c 
    on c."Customer ID" = fs.CustomerKey
GROUP BY 
    c."Customer ID",
    c.NAME,
    c.MonthlyIncome
于 2013-03-17T09:40:21.377 回答