我在数据库中有一些记录。现在我想从日期明智地得到记录。请看下面的格式我的表..
User_id name date Present
001 Jone 01-08-2012 yes
002 arun 01-08-2012 yes
001 Jone 02-08-2012 yes
002 arun 02-08-2012 yes
001 Jone 03-08-2012 yes
001 Jone 04-08-2012 yes
002 arun 05-08-2012 yes
001 Jone 05-08-2012 yes
001 Jone 06-08-2012 yes
001 arun 06-08-2012 yes
我希望从2012年8月1日到2012年7月7日这样的“arun”报告
User_id name date Present
002 arun 01-08-2012 yes
002 arun 02-08-2012 yes
002 arun 03-08-2012
002 arun 04-08-2012
002 arun 06-08-2012 yes
002 arun 07-08-2012
请帮我报告此内容。我是mysql的新手..
答案 0 :(得分:1)
为了显示缺少的日期,您需要一个临时表。 临时表:
CREATE TABLE numbers (number INTEGER);
INSERT INTO numbers VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
sql如下:
SELECT CASE WHEN u.id IS NOT NULL
THEN u.id
ELSE u2.id
END AS id ,
CASE WHEN u.name IS NOT NULL
THEN u.name
ELSE u2.name
END AS name ,
cal.date,
CASE WHEN u.present IS NOT NULL
THEN u.present
ELSE ''
END AS present
FROM (
SELECT '2012-08-01' + INTERVAL a.number * 10 + b.number DAY as date
FROM numbers a JOIN numbers b
ORDER BY a.number * 10 + b.number
) cal LEFT JOIN (select * from users where name='arun') u
ON DATE_FORMAT(STR_TO_DATE(u.date1, '%d-%m-%Y'), '%Y-%m-%d') = cal.date
left join (select id,name from users group by id)u2 on u.id is null and u2.name='arun'
WHERE date BETWEEN '2012-08-01' AND '2012-08-07';
答案 1 :(得分:0)
我认为这就是你要找的东西:
SELECT User_id, name, `date`,
IF(MAX(Present) = 1, 'yes', 'no') AS Present
FROM
(
SELECT User_id, name, `date`, IF('yes', 1, 0) Present
FROM table_name
WHERE `date` BETWEEN '2012-08-01' AND '2012-08-07' AND
name = 'arun'
UNION ALL
SELECT '002' AS User_id, 'arun' AS name, a.`date`, 0 AS Present
FROM (
SELECT CURDATE() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY AS date
FROM (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c
) a
WHERE a.date BETWEEN '2012-06-05' AND '2012-06-20';
) a
GROUP BY name, `date`
ORDER BY `date` ASC;
答案 2 :(得分:0)
select * from (
select id, name, date, present
FROM your_table
WHERE your_table.name = 'arun'
union all
select (select id from your_table where name = 'arun'), 'arun', all_dates.date, ''
from (select distinct date from your_table where your_table.name != 'arun')
left join your_table
ON all_dates.date = your_table.date
AND your_table.name = 'arun'
WHERE your_table.id IS NULL
) subquery
order by date desc
where date between '01-08-2012' and '07-08-2012'