1

我有一张像这样的桌子:

vending_machine_id | timestamp  | manual |
              543  | 2011-06-08 | true |
              543  | 2011-05-05 | false|
              543  | 2010-12-12 | true |
              542  | 2013-01-29 | true |
              542  | 2012-01-29 | true |

我想要的只是选择每个 vending_machine_id 的最新日期,并带有第三个字段 ( manual) 来拥有true/false(如果该 vending_machine_id 同时存在truefalserealdings,true(如果只有真正的手动读数),或false.

我做了这么多:

SELECT vmrp.vending_machine_id, max(timestamp), readingMethodSelect.readingMethod
FROM vending_machine_reading_product as vmrp,
(select 
    distinct(manual) as readingMethod, vending_machine_id
    FROM vending_machine_reading_product
    WHERE vending_machine_id in (542, 543, 821, 824)
    group by vending_machine_id, readingMethod) as readingMethodSelect
WHERE vmrp.vending_machine_id = readingMethodSelect.vending_machine_id
GROUP BY vmrp.vending_machine_id, readingMethodSelect.readingMethod
ORDER BY vmrp.vending_machine_id, max(timestamp) desc

它打印:

542;"2013-01-29 10:59:47";f
543;"2011-06-08 05:43:26";f
543;"2011-06-08 05:43:26";t
821;"2013-02-12 00:56:56";f
824;"2013-02-11 05:52:55";f

正如您所注意到的,我仍然不知道该怎么做是有一个带有543vending_machine_id 的单行,并且该行在末尾f/t。(因为这id有真假手动阅读类型)。

有什么办法可以做到这一点吗?

4

3 回答 3

3
SELECT  vending_machine_id, 
        MAX(timestamp) "TimeStamp",
        CASE WHEN COUNT(DISTINCT manual) > 1
            THEN 'True/False'
            ELSE MAX(manual)
        END AS "Manual"
-- WHERE ..add condition here..
FROM    TableName
GROUP   BY vending_machine_id
于 2013-04-24T14:38:55.390 回答
1

这是你想要的吗:

select vmrp.vending_machine_id, MAX(timestamp),
       bool_and(manual)
from vmrp.vending_machine_id
group by vmrp.vending_machine_id
于 2013-04-24T14:41:48.553 回答
0

尝试:

SELECT  vending_machine_id, 
        MAX(timestamp) "TimeStamp",
        array_agg(distinct manual order by manual desc)
FROM    TableName
GROUP   BY vending_machine_id

SQLFiddle在这里

于 2013-04-24T14:59:58.537 回答