2017-09-29 58 views
2

我有一個表結構如下MySQL的骨料由不同的初始值對另一列

| user_id | value | date  | 
|---------|-------|------------| 
| 1  | 5  | 2017-09-01 | 
| 2  | 6  | 2017-09-01 | 
| 1  | 1  | 2017-09-02 | 
| 1  | 2  | 2017-09-03 | 
| 2  | 9  | 2017-09-02 | 
| 1  | 3  | 2017-09-04 | 
| 2  | 5  | 2017-09-04 | 
| 2  | 5  | 2017-09-05 | 
| 1  | 1  | 2017-09-05 | 
| 1  | 5  | 2017-09-06 | 
| 1  | 6  | 2017-09-07 | 
| 1  | 3  | 2017-09-08 | 
| 1  | 4  | 2017-09-09 | 
| 2  | 6  | 2017-09-06 | 
| 1  | 1  | 2017-09-10 | 

我有其中用於user_ids初始截止日期被給予像

| user_id | date  | 
|---------|------------| 
| 1  | 2017-09-04 | 
| 2  | 2017-09-05 | 

最後截止日期的另一個表對於所有的用戶是2017-09-08

我想獲得由user_id聚合的值的總和

我已經試過是

SELECT user_id, SUM(value) as Total 
FROM table 
WHERE date >= $DATE and date <= '2017-09-08' 
GROUP BY user_id 

我堅持我應該如何處理$ DATE,因爲它是爲每個用戶

變量的情況下,解決方案應該是

| user_id | Total  | 
|---------|------------| 
| 1  | 18   | 
| 2  | 11   | 

回答

3

說您的表格名稱爲userscutoffcutoff具有每個用戶的截止日期。試試這個,讓我知道它是否有效。

select u.user_id,sum(u.value) Total 
from users u join cutoff c on u.user_id=c.user_id and (u.date>=c.date and u.date<='2017-09-08') 
group by u.user_id 
2
SELECT x.user_id, SUM(x.value) as Total 
FROM table x 
WHERE x.date >= (select date from table2 where user_id = x.user_id) 
and x.date <= '2017-09-08' 
GROUP BY x.user_id 
+0

相關的子查詢在MySQL中並沒有很好地實現,連接幾乎總是可取的。 – Barmar

+2

不是這種情況。子查詢非常簡單。 做一個1:M的樣本對性能不太有利。 – soft87

1

使用其中存在

SELECT a.user_id, SUM(a.value) as Total 
FROM table1 a 
WHERE EXISTS (
    SELECT 1 
    FROM table2 b 
    WHERE a.user_id = b.user_id 
    AND a.date >= b.date and a.date <= '2017-09-08' 
) 
GROUP BY user_id 

DEMO

或使用條件聚集

SELECT a.user_id, 
SUM(CASE WHEN a.date >= b.date and a.date <= '2017-09-08' 
    THEN a.value 
    ELSE 0 
    END) as Total 
FROM table1 a 
JOIN table2 b ON a.user_id = b.user_id 
GROUP BY user_id 

DEMO

+0

預期答案應如問題(18,11)中所述。從這個查詢我越來越(23,11) –

+1

@JayChakra我不好,這是表錯列b的錯位,現在糾正 –

+1

@M哈立德Junaid,單元測試忘了做=) – soft87