2012-06-26 70 views
3

我試過搜索,但它很可能我使用了錯誤的關鍵字,因爲我無法找到答案。SQL計數的開放式訂單每天之間的兩個日期

我試圖找到在兩個日期和員工之間打開的訂單數量。我有一張顯示員工名單的表格,另一張顯示包含開始和結束日期以及日期表格的訂單列表(如果有幫助的話)。

加盟將返回類似的員工和訂單表:

employee order ref opened   closed 
a   123   01/01/2012  04/01/2012 
b   124   02/01/2012  03/01/2012 
a   125   02/01/2012  03/01/2012 

,我需要這個數據轉換爲:

Date   employee Count 
01/01/2012  a   1 
02/01/2012  a   2 
02/01/2012  b   1 
03/01/2012  a   2 
03/01/2012  b   1 
04/01/2012  a   1 

我從SQL Server拉低數據。

任何想法?

感謝

尼克

+0

如果根本沒有行,你是否需要顯示零點? – Matthew

回答

0
SELECT opened,employee,count(*) 
FROM employee LEFT JOIN orders 
WHERE opened < firstDate and opened > secondDate 
GROUP BY opened,employee 

,或者你可以更改

WHERE opened BETWEEN firstDate and secondDate 
0

的首要條件調用結果列計數是有點古怪,因爲它似乎是事實上的行數。 你可以使用ROW_NUMBER來做到這一點。

另一個有趣的部分是,你也希望開放日期和關閉日期作爲單獨的行。使用簡單的聯合會解決這個問題。

WITH cte 
    AS (SELECT Row_number() OVER (PARTITION BY employee 
            ORDER BY order_ref) count, 
       employee, 
       opened, 
       closed 
     FROM orders) 
SELECT employee, opened date, count 
FROM cte 
UNION ALL 
SELECT employee, closed date, count 
FROM cte 
ORDER BY Date, 
      employee 

DEMO

0

我最喜歡的方式做到這一點計數的累計打開數和累計關閉隨時間的數量。

with cumopens as 
    (select employee, opened as thedate, 
      row_number() over (partition by employee order by opened) as cumopens, 
      0 as cumcloses 
    from eo 
    ), 
    cumcloses as 
    (select employee, closed as thedate, 0 as cumopens, 
      row_number() over (partition by employee order by closed) as cumcloses 
    from eo 
    ) 
select employee, c.thedate, max(cumopens), max(cumcloses), 
     max(cumopens) - max(cumcloses) as stillopened 
from ((select * 
     from cumopens 
    ) union all 
     (select * 
     from cumcloses 
    ) 
    ) c 
group by employee, thedate 

這種方法的唯一問題是隻有有員工活動的日期纔會被報告。這適用於你的情況。

更一般的解決方案需要序列號來生成日期。對於這一點,我經常有足夠的行一些現有的表創建一個:

with nums as 
    (select row_number() over (partition by null order by null) as seqnum 
    from employees 
    ) 
select employee, dateadd(day, opened, seqnum) as thedate, count(*) 
from eo join 
    nums 
    on datediff(day, opened, closed) < seqnum 
group by employee, dateadd(day, opened, seqnum) 
order by 1, 2 
+0

意外降落,現在我不能撤消了。抱歉。 – bertvh

2

加入DatesEmployeesOrders之間的連接的結果,然後按日期和職工組獲得的計數,是這樣的:

SELECT 
    d.Date, 
    o.Employee, 
    COUNT(*) AS count 
FROM Employees e 
    INNER JOIN Orders o ON e.ID = o.Employee 
    INNER JOIN Dates d ON d.Date BETWEEN o.Opened AND o.Closed 
GROUP BY 
    d.Date, 
    o.Employee 
相關問題