簡體   English   中英

MySQL使用單個表離開了連接

[英]MySQL left join with a single table

使用以下查詢獲取每小時的交易明細

SELECT hour(Stamp) AS Hour, count(1) AS Count FROM Transactions GROUP by 1 WITH ROLLUP;

結果如下:

+------+-------+
| Hour | Count |
+------+-------+
|    0 |   269 |
|    1 |   342 |
|    2 |   319 |
|    3 |   284 |
|    4 |   235 |
|    5 |   174 |
|    6 |    91 |
|    7 |    54 |
|    8 |    31 |
|    9 |    21 |
|   10 |    21 |
|   11 |     1 |
| NULL |  1842 |
+------+-------+

我想顯示0筆交易的小時數(例如,在此示例中,介於12到23之間的每小時將顯示'0')。 最簡單的方法是什么?

嘗試這樣的事情(-1 hour_id用於匯總總數):

drop table if exists hours;
create table hours(hour_id tinyint primary key) engine=innodb;

insert into hours (hour_id) values 
(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),
(13),(14),(15),(16),(17),(18),(19),(20),(21),(22),(23),(0),(-1);

select
 h.hour_id,
 if(t.counter is null, 0, t.counter) as counter
from
 hours h
left outer join 
(
 select 
    if(hour(stamp) is null, -1, hour(stamp)) as hour_id, 
    count(stamp) as counter
 from 
    transactions group by stamp with rollup
) t
on h.hour_id = t.hour_id;

如果你想要它幾個月創建一個月表1..12 + -1等...

SELECT Temp.Hour, COUNT(1)
FROM (
    SELECT 0  AS Hour 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
) AS Temp
LEFT JOIN Transactions
ON Temp.Hour = HOUR(Transactions.Stamp)
GROUP BY Temp.Hour
ORDER BY Temp.Hour

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM