将多个select语句结果集的结果合并到单个记录表中?

时间:2016-12-01 09:43:35

标签: sql-server

我有一个非常特别的问题。

我需要从我的存储过程中检索EmployeeID,UserID,TotalValue的Sum和COUNT的StartDate列的SUM作为单个记录。

场景:

如果我试试这个:

Select EmployeeID, UserID, Sum(TotalValue), Sum(Count(StartDate))
From Employees
Group By EmployeeID, UserID

问题是我不能同时使用Sum和Count,因为它会给我以下错误:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery

所以我做的是:

Select EmployeeID, UserID, TotalSummedValue, SUM(NoOfDates) FROM
(
 Select EmployeeID, UserID, SUM(TotalValue) AS TotalSummedValue, COUNT(StartDate)
 FROM Employees
 GROUP BY EmployeeID, UserID
) AS inner
GROUP BY EmployeeID, UserID

但现在问题是COUNT(StartDate)返回的值受内部查询中的分组的影响。 所以我基本上必须分别检索Count和其余的数据。

所以我做了一个基本查询(这是实际查询的简化版本),其结果我在临时表中插入并重用 - >

Insert Into #TempBase
SELECT EmployeeID, UserID, TotalValue, StartDate FROM Employees

并像这样使用它:

Insert INTO #Temp2
Select EmployeeID, UserID, SUM(TotalValue) AS TotalSummedValue FROM #TempBase

Insert INTO #Temp3
Select SUM(NoOfDates) FROM
(
 Select COUNT(StartDate) AS NoOfDates FROM
 #TempBase
)

然后,为了让整个事情在一个记录中出来,我现在正在做这个丑陋的事情:

Insert INTO #Temp4 (EmployeeID, UserID, TotalSummedValue, TotalDays)
Values((Select EmployeeID FROM #Temp2), (Select UserID FROM #Temp2),
(Select TotalSummedValue FROM #Temp2),(Select NoOfDates FROM #Temp3))

Select * from #Temp4    

我想知道是否有更好的方法可以做到这一点。

更新:  (列名与上面详述的示例不同)

Table Structure

Expected Result Set

[结果集包括 - 1)当天的EmployeeID,UserID,totalOrderValue 2)订单的不同日期总数]

我在查询中发现了问题,我正在使用此查询,这会导致计数结果偏差 -

Select EmployeeID , UserID, SUM(NoOfDays) AS TotalDays,SUM(SummedOrderValue) AS TotalOrderValue 
    FROM 
    (
     Select  EmployeeID, UserID,COUNT(DISTINCT OrderDate) AS NoOfDays,
     SUM(OrderValue) AS SummedOrderValue FROM BusinessEntity 
     GROUP BY OrderDate, EmployeeID, UserID, OrderValue
    ) AS o
    GROUP BY EmployeeID, UserID

但我意识到,我并不需要在内部Group By子句中使用OrderValue。删除它给了我正确的结果集 -

Select EmployeeID , UserID, SUM(NoOfDays) AS TotalDays,SUM(SummedOrderValue) AS TotalOrderValue 
FROM 
(
 Select  EmployeeID, UserID,COUNT(DISTINCT OrderDate) AS NoOfDays,
 SUM(OrderValue) AS SummedOrderValue FROM BusinessEntity 
 GROUP BY OrderDate, EmployeeID, UserID
) AS o
GROUP BY EmployeeID, UserID

0 个答案:

没有答案