2017-03-21 95 views
1

嗨我試圖計算從以下數據出現在過去三個月不止一次的不同accountids的數目;我想要2作爲查詢的結果,因爲[email protected][email protected]出現超過1次。MYSQL與某些特定數量的條目的列的總和

accountid   purchase requesttime 
[email protected] 150  2017-01-01 
[email protected] 100  2017-01-01 
[email protected] 100  2017-01-01 
[email protected] 200  2017-01-01 
[email protected] 240  2017-01-01 
[email protected] 210  2017-01-01 
[email protected] 4   2017-01-01 
[email protected] 60  2017-01-01 
+1

你規定的要求,你試圖查詢不匹配。如果您提供了適當的CREATE和INSERT語句以及期望的結果,這將會很有幫助。請參閱https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query – Strawberry

回答

1

我認爲你需要兩個級別的聚合。第一個返回符合條件的郵件:

select n.account_id, count(*) as cnt 
from ndsbulkstorage22 n 
where requesttime >= CURRENT_DATE - interval 3 month 
group by accountid 
having count(*) > 1; 

然後你可以使用它作爲一個子查詢:

select count(*) 
from (select n.account_id, count(*) as cnt 
     from ndsbulkstorage22 n 
     where requesttime >= CURRENT_DATE - interval 3 month 
     group by accountid 
     having count(*) > 1 
    ) n; 
-1

這個查詢將顯示結果要求的時間和一些外地購買3個月前。

MYSQL

select accountid,sum(purchase) as your_sum,requesttime from tbl_sum 
where requesttime <=DATE_ADD(requesttime,INTERVAL -3 month) GROUP BY accountid,requesttime 

MSQL

select accountid,sum(purchase) as your_sum,requesttime from tbl_sum 
where requesttime <=DATEADD(month,-3,requesttime) GROUP BY accountid,requesttim 
相關問題