2012-08-13 42 views
0

我一直坚持小查询。有一个名为Table_Activities的表。什么可以是这个优化的查询?

Table_ActivitiesAct_idDat E,Activity_namedescription)。

我们需要生成一份报告。用户将选择月份年份,他希望从下拉列表中生成报告。

我们需要按活动名称显示该月份和年份组的所有活动。

示例 - 用户选择June and 。

报告会是─

园艺

01/06/2012 - They have planted 100 trees. 
14/06/2012 - something 
27/06/2012 - something 

培训

02/06/2012 - Detail description 
15/06/2012 - something 
28/06/2012 - something 

我的问题是什么将是MySQL查询以这种格式来提取数据?

+0

你可以发表你的表(S)的模式? – 2012-08-13 06:33:41

+0

是“他们种了100棵树。”一个描述? – hims056 2012-08-13 06:49:18

回答

1
select `Date`,description from tm_activities 
where month(`Date`)='6' and year(`Date`)='2012' 
order by Activity_name,`date` 

返回准确的格式在你的问题指出,请尝试以下:如下

select concat(if(actdate='',activity_name,date_format(actdate,'%d/%m/%y')),if(description<>'',concat(' - ',description),'')) as labelm from 
(
(select ActDate,description,activity_name from tm_activities where month(ActDate)='6' and year(ActDate)='2012' 
) 
union all 
(Select distinct '','',activity_name from tm_activities where month(ActDate)='6' and year(ActDate)='2012') 
)m order by activity_name,actdate 
; 

SQL FIDDLE HERE.

输出:

Gardening 
01/06/12 - They have planted 100 trees. 
27/06/12 - Gar 2 
Training 
12/06/12 - Training 1 
28/06/12 - Traning 2 
30/06/12 - Traning 3 
+0

伟大的解决方案。向你致敬。 – user1545152 2012-08-13 07:30:10

+0

嗨,我们如何使用php在HTML页面上显示相同的内容。任何帮助将不胜感激。 – user1545152 2012-08-13 07:36:52

+0

在html页面上显示相同的意思是什么意思? – sel 2012-08-13 07:46:34

1

要获取ACTIVITY_NAME特定月份和年份组数据试试这个:

SELECT Activity_name 
,GROUP_CONCAT(DATE_FORMAT(Date,"%d/%m/%Y")) as `Date` 
,GROUP_CONCAT(Description) as `Description` 
FROM Table_Activities 
WHERE MONTH(Date) = MONTH('2012-06-01') 
AND YEAR(Date) = YEAR('2012-06-01') 
GROUP BY Activity_name 

输出

 
ACTIVITY_NAME DATE     DESCRIPTION 
----------------------------------------------------------------------------------- 
Gardening  01/06/2012,27/06/2012 They have planted 100 trees.,Description3 
Training   12/06/2012,28/06/2012 Description2,Description4 

See this SQLFiddle

0
Select 
    DATE_FORMAT('date_column',"%D/%M/%Y") as `Date`, 
    other_column 
from Table_Activities 
where Month(Date) = Month('2012-06-01') 
AND Year(Date) = Year('2012-06-01')