从另一个表中的日期之间的表中汇总数据

时间:2014-01-11 11:32:51

标签: php mysql joomla

我将这两个表与列itemid相互关联。 我设法在itemid的第一个示例中显示了不同data_table值的总和。

现在我想把这个总和与另一个表中的具体日期联系起来,但我不能。请有人帮帮我吗?

items_table

+--------+-----------+------------+
| itemid | published | publish_up |
+--------+-----------+------------+
|      1 |         1 | 02-01-2014 |
+--------+-----------+------------+

data_table

+--------+---------+------+
| itemid | fieldid | data |
+--------+---------+------+
|      1 |      27 |    5 |
|      1 |      28 |   10 |
|      1 |      29 |    5 |
+--------+---------+------+

此查询没问题:

SELECT (SELECT SUM(data) FROM data_table WHERE fieldid='27')
     + (SELECT SUM(data) FROM data_table WHERE fieldid='28')
     + (SELECT SUM(data) FROM data_table WHERE fieldid='29')

但不是在约会之间:

SELECT (SELECT SUM(data) FROM data_table WHERE fieldid='27')
     + (SELECT SUM(data) FROM data_table WHERE fieldid='28')
     + (SELECT SUM(data) FROM data_table WHERE fieldid='29')    
WHERE  (publish_up BETWEEN '2014-01-01 00:00:00' AND '2014-01-31 00:00:00') 
FROM   items_table

1 个答案:

答案 0 :(得分:0)

SELECT   itemid, SUM(data)
FROM     data_table JOIN items_table USING (itemid)
WHERE    publish_up >= '2014-01-01'
     AND publish_up <  '2014-02-01'
GROUP BY itemid