我有两张桌子。
Customer ID, NAME, MonthlyIncome
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
答案 0 :(得分: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
总数。
答案 1 :(得分:1)
您没有提到您正在使用的SQL Server的版本 - 但如果您使用的是SQL Server 2005 或更新版本,则可以使用{{ 1}}子句:
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
,CustomerKey
,然后为每个MonthlyIncome
汇总TotalCost
,并在输出中显示相应的值。在这种情况下无需执行CustomerKey
答案 2 :(得分:1)
您可能在联接的ON子句中有错误
您在CustomerKey
表格中使用了Customer ID
代替DimCustomer
。
对于gouping:您必须按照您未汇总的每个列进行分组,这样您就可以添加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