2010-08-18 87 views
0

表模式幫助建立這樣的:需要一個MySQL查詢分組

userID  Points  timestamp 

1   40 
3   20 
1   10 
4   15 
3   5 

需要能夠提交一份報告,顯示如下:

Total Points Allocated for the Day (0 if none allocated), (nice to have) To what userID's the points were allocated to for that day 

我嘗試以下以及你可以看到不正確

SELECT uid, DATE(time_stamp) AS date, SUM(points) AS total_points 
FROM table 
GROUP BY date 

回答

2

假設你有值作爲時間戳,我將使用列MES的用戶ID,分TIME_STAMP和userpoints的表名:

SELECT userID, 
     sum(points), 
     date(timestamp) as date 
FROM userpoints 
GROUP BY userID, date(timestamp) 

所以:

userID  Points  timestamp 

1   40   18-8-2010 12:00:00.000 
3   20   18-8-2010 12:00:00.000 
1   10   18-8-2010 12:00:00.000 
4   15   18-8-2010 12:00:00.000 
3   5   18-8-2010 12:00:00.000 

會導致:

userid  points  date 
1   50   18-8-2010 
3   25   18-8-2010 
4   15   18-8-2010 

UPDATE:精緻的UNIX發行

SELECT userID, 
     sum(points), 
     from_unixtime(timestamp, 'DD-MM-YYYY') as date 
FROM userpoints 
GROUP BY userID, date(timestamp) 
+0

時間戳未正確輸入。我的意思是我看到很多NULLS,並且日期是錯誤的。今天應該是什麼東西,我看到2012. – jini 2010-08-18 18:04:08

+0

你用什麼來填充你的桌子? – XstreamINsanity 2010-08-18 18:06:41

+0

時間戳只是一個unix時間戳。所以我有像1256235850,1256255246這樣的值,當你做日期(時間戳) – jini 2010-08-18 18:12:15

1
SELECT DATE(time_stamp) as date1, userID, SUM(Points) as total_points 
FROM table1 
GROUP BY date1, userID 
WITH ROLLUP 

具有空userID且不爲空的記錄date1顯示該日期分配的點數, 具有空userID和空date1的記錄 - 分配的總點數。

+0

我喜歡那個ROLLUP。以前從未見過/使用過。尼斯。 – XstreamINsanity 2010-08-18 18:06:21

2

MySQL沒有遞歸功能,所以你只需要使用NUMBERS表格技巧來獲取一個日期列表,以便在出現零關係歸屬的日子裏進行LEFT JOIN。

  1. 創建一個只持有遞增的數字表 - 易使用AUTO_INCREMENT做:

    DROP TABLE IF EXISTS `example`.`numbers`; 
    CREATE TABLE `example`.`numbers` (
        `id` int(10) unsigned NOT NULL auto_increment, 
        PRIMARY KEY (`id`) 
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1; 
    
  2. 使用填充表:

    INSERT INTO NUMBERS 
        (id) 
    VALUES 
        (NULL) 
    

    ...儘可能多的價值如你所需。

  3. 使用DATE_ADD構建的時間列表的基礎上,NUMBERS.id值增加月:

    SELECT x.* 
        FROM (SELECT DATE_ADD('2010-01-01', INTERVAL n.id - 1 DAY) 
          FROM numbers n) x 
    
  4. LEFT JOIN到你的基礎上的日期時間部分的數據表:

    SELECT up.userid, 
          COALESCE(SUM(up.points), 0) AS points 
          DATE(x.dt) AS date 
        FROM (SELECT DATE_ADD('2010-01-01', INTERVAL n.id - 1 MONTH) AS dt 
          FROM numbers n) x 
    LEFT JOIN USERPOINTS up ON DATE(FROM_UNIXTIME(up.timestamp)) = DATE(x.dt) 
    GROUP BY up.userid, DATE(x.dt)