2014-06-25 142 views
3

我有2個表:部門和銷售。在我的部門表中,我有一個勞動部門編號和它所關聯的銷售部門的編號。我也想讓部門的銷售「彙總」到另一個部門。我需要幫助查詢「彙總」銷售。總計有條件分組

下面是表:

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` 

但我該怎麼做「彙總」?我試圖把一個案例陳述在這樣的聯合中,像這樣:

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

非常感謝所有3個答案。我在概念上喜歡cte方法,但它對我沒有用(可能是我做錯了,我假設)。 DavidN的解決方案最終很容易理解,並在大約20K行數據上表現良好。謝謝。 –

回答

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) 
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 
+0

在我的測試中,這個比DavidN好一點,因爲它只有一個讀取到每個表,而不是兩次讀取部門表。 –

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的更好。