2014-10-16 33 views
1

我試圖跟蹤銷售代表的總數以及他的工作時間。SQL Group按相同條目號發行

我有以下兩個表:

表1:

employeeID | item | price | timeID 
---------------------------------------- 
1   | 1 | 12.92 | 123  
1   | 2 | 10.00 | 123  
1   | 2 | 10.00 | 456  

表2:

ID | minutes_in_shift 
-------------------------- 
123  | 45 
456  | 15 

我會加入這兩個查詢用下面的SQL:

SELECT 
    t1.employeeID, t1.item, t1.price, t1.shiftID, t2.minutes_in_shift 
FROM table1 t1 
JOIN table 2 t2 ON (t2.ID = t1.timeID) 

其中將下面的表格返回:

employeeID | item | price | timeID | minutes_in_shift 
--------------------------------------------------- 
1   | 1 | 12.92 | 123 | 45 
1   | 2 | 10.00 | 123 | 45 
1   | 2 | 10.00 | 456 | 15 

我想爲鞏固成果,然而,有這樣的結果:

employeeID | itemsSold | priceTotals | totaltimeworked 
----------------------------------------------------------------- 
    1   |  3  | 32.92  |  60 

我可以使用COUNT和SUM的項目和價格,但我想不出瞭解如何正確顯示上面顯示的總時間。 注意:我只在計算工作時間時遇到麻煩。在班次123中 - 員工1工作了45分鐘,無論他售出多少物品。

有什麼建議嗎?

+0

對於itemsSold和priceTotals使用'select employeeID,count(*),sum(price)group by employeeID'。你如何計算總工時? – cha 2014-10-16 23:54:22

+0

cha - 物品表是一個,它被連接到一個時間表,它顯示了存儲的時間量。這是字面上的時間(123輪班,45分鐘,456輪,15分鐘waas,無論賣出什麼物品) – JM4 2014-10-16 23:55:28

+0

這是可以從你的樣本中完成的。但是,如果您可以向我們展示用於構建您的示例的源SQL,我們可以優化它以立即得到期望的結果 – cha 2014-10-16 23:59:16

回答

3

如果你希望,因爲他們是你需要提取的變化,總結了幾分鐘,像這樣用樣本數據:

with a as (
    select employeeID, count(*) itemsSold, sum(price) priceTotals 
    from Sampletable1 
    group by employeeID), 
b as (
    select employeeID, shiftID, max(minutes_in_shift) minutes_in_shift 
    from Sampletable1 
    group by employeeID, shiftID), 
c as (
    select employeeID, sum(minutes_in_shift) totaltimeworked 
    from b 
    group by employeeID) 
select a.employeeID, a.itemsSold, a.priceTotals, c.totaltimeworked 
from a inner join c on a.employeeID = c.employeeID 

然而,與現有的表中的select語句會容易得多:

with a as (
    select employeeID, timeID, count(*) itemsSold, sum(price) priceTotals 
    from table1 
    group by employeeID, timeID) 
select a.employeeID, sum(a.itemsSold), sum(a.priceTotals), sum(table2.minutes_in_shift) totaltimeworked 
from a inner join table2 on a.timeID = table2.ID 
group by a.employeeID 
1

我覺得這個查詢應該做你想要什麼:

SELECT t1.employeeID, 
     count(t1.item)     AS itemsSold, 
     sum(t1.price)      AS priceTotals, 
     sum(DISTINCT t2.minutes_in_shift) AS totaltimeworked 
    FROM table1 t1 
    JOIN table2 t2 ON (t2.ID = t1.timeID) 
GROUP BY t1.employeeID; 

Check on SQL Fiddle

+0

這可能實際上是更快且準確的查詢,因爲分鐘永遠不會使用相同的shiftID更改。謝謝@vyegorov – JM4 2014-10-17 18:56:18

+0

請謹慎使用此查詢。如果您有相同數量的分鐘的不同班次,則查詢會將它們統計爲一個併產生錯誤的結果 – cha 2014-10-19 09:48:13