1

同じステートメントで、曜日と時間に基づいてデータを抽出しようとしています(これにより、1時間あたりおよび1週間に何回の訪問があったかを確認できます。ステートメントは次のとおりです。

SELECT
count(id) as count,
HOUR(created) as hour_of_day,
WEEKDAY(created) as day_of_week,
DATE_FORMAT(created,'%W') name_of_day
FROM visitors
GROUP BY day_of_week,hour_of_day
ORDER BY day_of_week,hour_of_day ASC

いくつかのサンプルデータ

    count   hour_of_day day_of_week name_of_day
    2       0           0           Monday
    1       1           0           Monday
    1       4           0           Monday
    4       5           0           Monday
    1       6           0           Monday
    4       7           0           Monday
    1       9           0           Monday
    1       10          0           Monday
    1       12          0           Monday
    1       13          0           Monday
    2       16          0           Monday
    5       18          0           Monday
    5       19          0           Monday

問題 ご覧のとおり、データには何時間にもわたってデータが欠落しています。そして、最初の出力から始まる24時間のタイムラインと一致する、毎日[x、x、x、x、x、x、x]の形式のデータを必要とするグラフを作成しているので、欠落しているものは「0」になります。

PHP側ではループを使用して処理できますが、曜日ごと、およびその範囲内で1時間ごとにループするのはかなり面倒で、間違いなくクリーンではありません。

一時的なテーブルなしで可能ですか(クエリ自体に24桁を含めるなど)?

4

2 に答える 2

2

かわいくない。ただし、一時テーブルを実際に使用できない場合は、このトリックを実行する必要があります。

select ifnull(count,0) as count,dh.hour_of_day,
dh.day_of_week,date_format((date('2012-01-02') + interval dh.day_of_week day),'%W') as name_of_day
from
(
select day_of_week,hour_of_day
from 
(
 select 0 as day_of_week union select 1 union select 2 union select 3 
 union select 4 union select 5 union select 6
) d
 join
(
 select 0 as hour_of_day 
 union select 1 union select 2 union select 3 union select 4 
 union select 5 union select 6 union select 7 union select 8
 union select 9 union select 10 union select 11 union select 12
 union select 13 union select 14 union select 15 union select 16
 union select 17 union select 18 union select 19 union select 20
 union select 21 union select 22 union select 23
) h
) dh
left outer join
(
SELECT
count(id) as count,
HOUR(created) as hour_of_day,
WEEKDAY(created) as day_of_week,
DATE_FORMAT(created,'%W') name_of_day
FROM visitors
GROUP BY day_of_week,hour_of_day
) v on dh.day_of_week = v.day_of_week and dh.hour_of_day = v.hour_of_day
ORDER BY dh.day_of_week,dh.hour_of_day ASC; 

ただし、これには注意してください。複数の週にわたってクエリを実行すると、複数の曜日が一緒に追加されます。'今週のみ'述語を追加することを検討することをお勧めします。たとえばwhere yearweek(created) = yearweek(now())、元の選択に追加して、今週のデータのみを取得します。

于 2012-01-04T11:43:48.970 に答える
0

Not sure why you don't want to use temp tables, it makes life much easier.

the solution is best laid out here: http://www.freeopenbook.com/mysqlcookbook/mysqlckbk-chp-12-sect-10.html

Essentially you would have to create a table with all the hours in a day and left join on it.

于 2012-01-04T11:23:31.323 に答える