SQL查询并仅显示日期

时间:2014-08-13 23:30:14

标签: mysql mysqli

CREATE TABLE `celula` (
  `ID_Celula` int(255) unsigned NOT NULL AUTO_INCREMENT,
  `integrantes` text,
  PRIMARY KEY (`ID_Celula`)
);

INSERT INTO `celula` (`ID_Celula`, `integrantes`) VALUES
(1, '2:2014-08-13,4:2014-08-13,6:2014-08-13,7:2014-08-13'),
(2, '3:2014-08-13,5:2014-08-13,6:2014-08-13');

如何仅显示列成员的日期?

在线测试http://sqlfiddle.com/#!2/1729fd/4

我感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情

SELECT YEAR(date) year, MONTH(date) month, COUNT(*) count
  FROM
(
  SELECT SUBSTRING_INDEX(value, ':', 1) id, 
         CAST(SUBSTRING_INDEX(value, ':', -1) AS DATE) date
    FROM
  (
    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(integrantes, ',', n), ',', -1) value
      FROM celula CROSS JOIN 
    (
      SELECT a.N + b.N * 10 + 1 n
      FROM 
      (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
     ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ) tally
     WHERE n <= 1 + (LENGTH(integrantes) - LENGTH(REPLACE(integrantes, ',', '')))
  ) q
) o
 GROUP BY YEAR(date), MONTH(date)

输出:

| YEAR | MONTH | COUNT |
|------|-------|-------|
| 2014 |     8 |     7 |

这是 SQLFiddle 演示

如果您需要拆分超过100个值,您可以轻松地调整最内层SELECT以生成更多行,或者甚至可以简化您使其成为数据库中的持久(计数)表的内容