我有2个表:部门和销售。在我的部门表中,我有一个劳工部门ID和与之关联的销售部门的ID。我还希望允许部门的销售人员来“累积”#34;到另一个部门。我需要帮助查询"汇总"销售。
以下是表格:
TABLE = Departments
LaborDeptid | AssociatedSalesDept | RollUpTo
1 101 0
2 102 0
3 103 1
4 104 0
TABLE = Sales
Date | Sales | SalesDept
1/1/2014 10.00 101
1/1/2014 10.00 101
1/1/2014 10.00 102
1/1/2014 10.00 102
1/1/2014 10.00 103
1/1/2014 10.00 103
1/1/2014 10.00 104
1/1/2014 10.00 104
这是我想要的输出:
OUTPUT
Date | LaborDept | TotalSales
1/1/2014 1 40.00
1/1/2014 2 20.00
1/1/2014 4 20.00
如您所见,劳动部门1包括销售部门101和103的销售。但我不知道如何做到这一点。按部门汇总的查询很容易:
select
Date,
LaborDept,
sum(sales) as TotalSales
from sales s
inner join departments d on s.SalesDept = d.AssociatedSalesDept
group by Date,LaborDept`
但我怎么做"汇总"?我尝试在连接中添加一个case语句,如下所示:
select
sum(sales) as TotalSales,
Date,
LaborDept
from sales s
inner join departments d on s.SalesDept = case when d.RollUpTo <> 0 then
(select AssociatedSalesDept
from departments
where d.RollUpTo = LaborDeptID)
else d.AssociatedSalesDept end
group by Date,LaborDept
但这只是将103个销售部门全部放在一起。它似乎不是正确的做法。
答案 0 :(得分:2)
select s.[Date], coalesce(d2.LaborDeptid,d1.LaborDeptid) [LaborDept], sum(s.Sales) [TotalSales]
from Sales s
join Departments d1 on s.SalesDept = d1.AssociatedSalesDept
left join Departments d2 on d1.RollUpTo = d2.LaborDeptid
group by s.[Date], coalesce(d2.LaborDeptid,d1.LaborDeptid)
答案 1 :(得分:2)
我不得不考虑这一点,但这是一个解决方案:
WITH cte AS (
SELECT CASE WHEN RollUpTo = 0 THEN LaborDeptId ELSE RollUpTo END AS LaborDeptId, AssociatedSalesDept
FROM departments)
SELECT s.date, d.LaborDeptid, SUM(s.Sales) AS TotalSales
FROM Sales s
INNER JOIN cte d ON s.SalesDept = d.AssociatedSalesDept
GROUP BY s.date, d.LaborDeptid
答案 2 :(得分:1)
SELECT s.Date,
d.LaborDeptId,
SUM(Sales) + ISNULL((SELECT
CASE Departments.RollUpTo
WHEN 0 THEN SUM(0)
ELSE SUM(Sales)
END
FROM Departments
INNER JOIN Sales ON Departments.AssociatedSalesDept = Sales.SalesDept
WHERE Departments.RollUpTo = d.LaborDeptId
AND Departments.RollUpTo <> 0
GROUP BY Departments.RollUpTo), 0) AS TotalSales
FROM Departments d
INNER JOIN Sales s ON d.AssociatedSalesDept = s.SalesDept
WHERE d.RollUpTo = 0
GROUP BY s.Date, d.LaborDeptId, d.RollUpTo;
使用子查询的另一个选项。我喜欢DavidN更好。