2016-12-09 53 views
0

我在編寫sql查詢時遇到了一些麻煩。Postgres從其他幾個表中選擇與主表關係

我在我的postgres數據庫中有3個表。

Table devices: 
    - dev_id (PK) 
    - device_type (varchar) 

Table thermomether_values: 
    - status_id (PK) 
    - error (boolean) 
    - receive_time (datetime) 
    - device_id (FK to table devices) 
    - value (varchar) 

Table camera_values: 
    - status_id (PK) 
    - error (boolean) 
    - receive_time (datetime) 
    - device_id (FK to table devices) 
    - value (decimal) 

有一些設備類型,如thermomether,照相機等

在表「some_device_values」和「another_device_values」每分鐘被保存從設備中讀取某個值。

有時當設備出現問題時,字段「錯誤」爲真。 我想獲得所有條目,哪裏出現錯誤(status_id和device_id是足夠的),但只有每個設備的最新(按receive_time desc排序,只得到第一個)。

的樣本數據:

Table devices: 
    dev_id device_type 
    1  THERMOMETHER 
    2  CAMERA 
    3  AC 
    4  THERMOMETHER 
    5  CAMERA 

Table thermomether_values: 
    status_id error receive_time  device_id value 
    1   false 09-12-2016 10:30 1   36.5*C 
    2   false 09-12-2016 10:30 4   15.0*C 
    3   false 09-12-2016 10:31 1   36.5*C 
    4   false 09-12-2016 10:32 1   36.5*C 
    5   true 09-12-2016 10:32 4   10.5*C 
    6   true 09-12-2016 10:33 4   11.5*C 


Table camera_values: 
    status_id error receive_time  device_id value 
    1   false 09-12-2016 10:30 2   54.23 
    2   true 09-12-2016 10:31 2   0.0 
    3   false 09-12-2016 10:31 5   50.76 
    4   true 09-12-2016 10:32 2   0.0 
    5   true 09-12-2016 10:32 5   -1.0 
    6   false 09-12-2016 10:33 2   54.3 

從上面的數據輸出應該是:

status_id device_id 
6   4   (thermomether) 
5   5   (camera) 

這是一個有點複雜了我,我不知道從哪裏開始。你可以幫我嗎?

+1

** [編輯] **你的問題,並添加基於該數據的一些樣本數據和預期輸出。 [**格式**](http://stackoverflow.com/help/formatting)**文本**請[無屏幕截圖](http://meta.stackoverflow.com/questions/285551/why-may -i-not-upload-images-of-code-on-so-when-asking-question-285557#285557) –

回答

0

窗口函數呢?

下面是一些小愚蠢的例子:

with srcdata as (
    select * 
    from (values(10,1,'A'),(10, 2,'B'),(11,1,'X'),(11,2,'Z')) as t(device,event, value) 
) 
select * 
from (
    select *, row_number() over w as rowid 
    from srcdata 
    window w as (partition by device order by event) 
) a 
where rowid=1 
+3

不相關,但是:你可以簡化爲'with srcdata(device,event,value)as (值(....)' - 不需要「從值中選擇」 –