如何为另一个表中的所有组重复表中的所有行?
答案 0 :(得分: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
答案 1 :(得分: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)
答案 2 :(得分: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
答案 3 :(得分: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