简体   繁体   中英

What can be the optimized query for this?

I have stuck in small query. There is a table named Table_Activities.

Table_Activities ( Act_id , Dat e, Activity_name , description ).

We need to generate a report out of this. User will choose the month and year for which he wants to generate the report from drop down list.

We need to display All the activities for that month and year group by Activity name.

Example - User Chooses June and 2012 .

Report will be-

Gardening

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

Training

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

My question is what will be the mysql query to fetch data in this format??

To get data for particular month and year group by Activity_name try this:

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 

Output

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

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

To return an exact format as indicated in your question, please try below:

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.

Output as below:

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
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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM