2012-08-13 43 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')