我有一个MySQL表(place_analytics),我想使用group_concat按地址获取每月的计数,
我试过了,
SELECT place_id,
GROUP_CONCAT(
DISTINCT MONTHNAME(STR_TO_DATE(MONTH(created_at), '%m'))
) AS months,
COUNT(*) AS place_count
FROM place_analytics
GROUP BY place_id
这给了我几乎正确的结果,
如果你查看第三行,即
place_id | months | place_count
4 | July, June | 2
计数是我所有月份的总和:7月,6月。
问题: 有没有办法让我每个月都能使用group_concat来计算,如下所示,
place_id | months | place_count
4 | July, June | 1,1
或者这种格式也可以,
place_id | months_and_count
4 | July,1 SEPARATOR June,1
CREATE TABLE `place_analytics` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`place_id` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`is_followed` tinyint(4) NOT NULL DEFAULT '0',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- ----------------------------
-- Records of place_analytics
-- ----------------------------
INSERT INTO `place_analytics` VALUES ('1', '10', '6', '0', '2017-06-01 15:45:04');
INSERT INTO `place_analytics` VALUES ('2', '98', '1', '1', '2017-06-01 15:45:39');
INSERT INTO `place_analytics` VALUES ('3', '98', '3', '1', '2017-06-01 15:46:24');
INSERT INTO `place_analytics` VALUES ('4', '10', '5', '1', '2017-06-01 17:51:27');
INSERT INTO `place_analytics` VALUES ('5', '98', '5', '1', '2017-06-01 17:53:48');
INSERT INTO `place_analytics` VALUES ('6', '98', '5', '1', '2017-06-08 15:43:27');
INSERT INTO `place_analytics` VALUES ('7', '1', '5', '1', '2017-06-08 15:47:56');
INSERT INTO `place_analytics` VALUES ('8', '2', '5', '1', '2017-06-08 16:00:43');
INSERT INTO `place_analytics` VALUES ('9', '4', '5', '1', '2017-06-09 16:21:19');
INSERT INTO `place_analytics` VALUES ('10', '4', '2', '1', '2017-07-13 14:29:45');
答案 0 :(得分:1)
SELECT Z.place_id,GROUP_CONCAT(Z.place_count),GROUP_CONCAT(Z.months) months
FROM
(
SELECT place_id,
GROUP_CONCAT(
DISTINCT MONTHNAME(STR_TO_DATE(MONTH(created_at), '%m'))
) AS months,
COUNT(*) AS place_count
FROM place_analytics
GROUP BY place_id,MONTHNAME(STR_TO_DATE(MONTH(created_at), '%m'))
)Z
GROUP BY place_id
尝试以上查询。
答案 1 :(得分:0)
尝试以下查询:
SELECT p.place_id,
GROUP_CONCAT(
DISTINCT MONTHNAME(STR_TO_DATE(MONTH(p.created_at), '%m'))
) AS months,
(SELECT GROUP_CONCAT(cnt) FROM (
SELECT COUNT(*) AS cnt FROM place_analytics GROUP BY place_id, MONTH(created_at)
) a) AS place_count
FROM place_analytics p
GROUP BY place_id;
这里是 SQL Fiddle 。