2016-08-01 66 views

回答

1

試試這個,

SELECT d.*, dp.dept, u.users_created 
FROM dbo.dates d 
CROSS APPLY (SELECT DISTINCT dept FROM dbo.users) as dp 
OUTER APPLY (SELECT COUNT(*) users_created 
       FROM dbo.users u 
       WHERE u.dept = dp.dept 
       AND u.created_at >= d.month_start 
       AND u.created_at < d.next_month_start 
      ) as u 
2

從指定的日期做一個簡單的SELECT COUNT?

SELECT month_start, next_month_start, sum(cnt) as users, dept FROM 
(SELECT CASE WHEN created_at<=next_month_start AND created_at>=month_start THEN 1 ELSE 0 END as cnt, 
users.*, month_start, next_month_start FROM users 
CROSS JOIN dates) as S1 
GROUP BY dept, month_start, next_month_start ORDER BY dept DESC 
+0

我不知道該怎麼做。你能幫忙編寫一個查詢來生成我的問題的結果嗎? – user130268

+0

對不起,添加了查詢。適用於我。 –

1
SELECT D.id dates_id,D.month_start dates_start,D.next_month_start dates_next_month_start,count(U.id) user_created,U.dept 

FROM dates D 
LEFT JOIN users U ON concat(year(U.created_at) ,"-",month(U.created_at)) = concat(year(D.month_start) ,"-",month(D.month_start)) 

GROUP BY concat(year(D.month_start) ,"-",month(D.month_start)) ,concat(year(D.next_month_start) ,"-",month(D.next_month_start)) ; 

以下是出把

id month_start     next_month_start    user_created dept 
7 February, 01 2016 00:00:00 March, 01 2016 00:00:00  0    (null) 
6 March, 01 2016 00:00:00  April, 01 2016 00:00:00  2    sales 
5 April, 01 2016 00:00:00  May, 01 2016 00:00:00   3    sales 
4 May, 01 2016 00:00:00  June, 01 2016 00:00:00  0    (null) 
3 June, 01 2016 00:00:00  July, 01 2016 00:00:00  2    hr 
2 July, 01 2016 00:00:00  August, 01 2016 00:00:00  0    (null) 
1 August, 01 2016 00:00:00 September, 01 2016 00:00:00 0    (null) 
+0

這與我所需要的不一樣。請注意,我需要重複'用戶'表中每個部門的整個'日期'表。在我的問題中查看ascii表。這就是我想要的。 – user130268

+0

你還使用SQL Server作爲數據庫嗎?嘗試執行時出現語法錯誤。看起來「_」在SQL Server中無效。 – user130268

+0

我在這裏使用http://sqlfiddle.com/#!9/fd212/7 – Athar

1

您是否需要這樣的事?

SELECT sum(cnt), month_start, next_month_start, dept 
FROM 
(
    SELECT 
    CASE WHEN created_at<=next_month_start AND created_at>=month_start THEN 1 ELSE 0 END cnt, 
    users.*, month_start, next_month_start 
    FROM users 
    CROSS JOIN dates 
) sbt 
GROUP BY month_start, next_month_start, dept 
相關問題