2014-01-11 59 views
1

我有這兩個表相互關聯的列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 

回答

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 
+0

那麼,但使用JDatabaseQuery來做到這一點。 – Elin

+0

thx非常多...! – sebas

+0

SELECT SUM(data)FROM data_table WHERE fieldid IN(SELECT itemid FROM items_table WHERE(publish_up BETWEEN'2014-01-01 00:00:00'AND'2014-01-31 00:00:00')) – sebas

相關問題