0

我有一个查询,以获取基于每个月和国家/地区的购买商品数量。

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

我不想重复“县”。有没有办法做到这一点。

4

2 回答 2

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

于 2012-05-09T12:38:23.143 回答
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
于 2012-05-09T12:58:55.790 回答