我有一个查询,可根据每个月和每个国家/地区获取所购商品的数量。
SELECT COUNT( `country` ) as item,
`country`,
MONTH(purchase_date) AS Month,
YEAR( purchase_date) AS year
FROM charmy_purchase
WHERE YEAR(purchase_date)='20112'
GROUP BY country,MONTH(purchase_date)
ORDER BY country ASC
我得到了这个结果。
item country Month year
2 India 5 2012
1 India 6 2012
1 Malasiya 5 2012
3 Singapure 1 2012
1 Singapure 4 2012
我不想重复这个'国家'。有没有办法做到这一点。
答案 0 :(得分:1)
目前尚不清楚您期望的输出。但您可以从MONTH(purchase_date)
GROUP BY country,MONTH(purchase_date)
SELECT COUNT( `country` ) as item,
`country`,
MONTH(purchase_date) AS Month,
YEAR( purchase_date) AS year
FROM charmy_purchase
WHERE YEAR(purchase_date)='2012'
GROUP BY country
ORDER BY country ASC
这将为您提供不同的国家/地区。但如果一个国家有更多,那么它也会给你任何月份和年份。
如果您希望将月份和年份以逗号分隔的一行列出,请尝试以下操作:
SELECT COUNT( `country` ) as item,
`country`,
group_concat(MONTH(purchase_date)) AS Months,
YEAR( purchase_date) AS year
FROM charmy_purchase
WHERE YEAR(purchase_date)='2012'
GROUP BY country
ORDER BY country ASC
请参阅此示例:SQLFiddle
答案 1 :(得分:0)
尝试group_concat,如下所示:
SELECT COUNT( `country` ) as item,
`country`,
GROUP_CONCAT(MONTH(purchase_date)) AS Months,
YEAR( purchase_date) AS year
FROM charmy_purchase
WHERE YEAR(purchase_date)='2012'
GROUP BY country
ORDER BY country ASC