2017-04-19 32 views
2

再次根據其他數據集對數據進行統計。試圖根據另一個參數獲取數據的統計信息

我有一個客戶名單。像下面這樣:

CustomerID Value Date 
1   3  01/01/2017 
2   2  01/02/2017 
3   1  01/02/2017 
1   5  01/04/2017 
1   6  01/04/2017 
2   1  01/04/2017 
2   2  01/04/2017 

我想獲得一個平均日期範圍的天凡客2還具有價值的客戶1。有人有想法嗎?

例如

Select avg(value) 
from Table where customerid=1 
and (customer 2 values are not blank) 
and date between '01/01/2017' and '01/31/2017' 

我使用SQL Server Express 2012

+0

你想一個平均的所有天或每天一個平均? –

回答

1

另一種選擇

Select AvgValue = Avg(Value+0.0) -- Remove +0.0 if you want an INT 
From YourTable 
Where CustomerID = 1 
    and Date in (Select Distinct Date from YourTable Where CustomerID=2) 

返回

AvgValue 
5.500000 
1

可以使用existsin選擇的日期,然後計算平均值:如果你想

select avg(value) 
from datatbl t 
where customerid = 1 and 
     exists (select 1 from datatbl t2 where t2.customerId = 2 and t2.date = t.date); 

平均爲,日期爲,則包括group by date

+0

感謝您的快速回復!我很抱歉,但t和t2令我困惑。如果我的表的名稱是 「Datatbl」 我會寫它想: 從datatbl 選擇AVG(值) 其中客戶id = 1和 存在(從datatbl datatbl2其中datatbl2.customerID = 2 和datatbl2.date = datatbl選擇1 .date 對不起,我知道這是一個天真的問題... – Shnozz

+0

讓我換個話題,如果我的表名是Datatbl,我的查詢應該是什麼樣子?我假設't'和't2'是引用數據我應該知道,但我沒有得到它... – Shnozz

相關問題