回答編集履歴

1

sample

2016/11/22 08:22

投稿

yambejp
yambejp

スコア114779

test CHANGED
@@ -11,3 +11,123 @@
11
11
  いずれにしろ、テーブルとかんたんなサンプルを表記し、
12
12
 
13
13
  期待する結果を提示していただいたほうが適切な回答がつきやすいと思います
14
+
15
+
16
+
17
+ # sample
18
+
19
+ ```SQL
20
+
21
+ create table wp_posts(ID bigint(20) unsigned not null primary key auto_increment,post_date datetime);
22
+
23
+ insert into wp_posts values(1,'2016-01-01 00:00:00'),(2,'2016-01-01 01:00:00'),(3,'2016-01-02 00:00:00'),(4,'2016-02-01 00:00:00'),(5,'2016-02-01 01:00:00'),(6,'2016-03-01 00:00:00'),(7,'2017-01-01 00:00:00');
24
+
25
+
26
+
27
+ ```
28
+
29
+ だったとして、抽出するSQLは
30
+
31
+ ```SQL
32
+
33
+ select year(post_date) as year
34
+
35
+ ,month(post_date) as month
36
+
37
+ ,count(*) as count
38
+
39
+ from wp_posts
40
+
41
+ group by year,month
42
+
43
+ order by year desc,month desc;
44
+
45
+ ```
46
+
47
+ すると結果は
48
+
49
+ ```ここに言語を入力
50
+
51
+ year month count
52
+
53
+ 2017 1 1
54
+
55
+ 2016 3 1
56
+
57
+ 2016 2 2
58
+
59
+ 2016 1 3
60
+
61
+
62
+
63
+ ```
64
+
65
+ なり、PHPでいうとこんな感じ
66
+
67
+
68
+
69
+ ```ここに言語を入力
70
+
71
+ /*抽出部分は省略*/
72
+
73
+ $months=[
74
+
75
+ (object) ["year"=>2017,"month"=>1,"count"=>1],
76
+
77
+ (object) ["year"=>2016,"month"=>3,"count"=>1],
78
+
79
+ (object) ["year"=>2016,"month"=>2,"count"=>2],
80
+
81
+ (object) ["year"=>2016,"month"=>1,"count"=>3],
82
+
83
+ ];
84
+
85
+ $html="";
86
+
87
+ $pre_year=0;
88
+
89
+ foreach($months as $key=>$month){
90
+
91
+ $year=$month->year;
92
+
93
+ if($pre_year!==$year){
94
+
95
+ if($key>0){
96
+
97
+ $html.="</ul>\n";
98
+
99
+ $html.="</div>\n";
100
+
101
+ }
102
+
103
+ $html.="<div>\n";
104
+
105
+ $html.=sprintf("<h4>%s年</h4>\n",$year);
106
+
107
+ $html.="<ul>\n";
108
+
109
+ }
110
+
111
+ $html.=sprintf("<a href='#'>%s月(%s)</a></li>\n",$month->month,$month->count);
112
+
113
+ $pre_year=$year;
114
+
115
+ }
116
+
117
+ if(count($months)>0){
118
+
119
+ $html.="</ul>\n";
120
+
121
+ $html.="</div>\n";
122
+
123
+ }
124
+
125
+ print "<pre>\n";
126
+
127
+ print htmlspecialchars($html);
128
+
129
+ print "</pre>\n";
130
+
131
+
132
+
133
+ ```