简体   繁体   中英

How to solve a complex group by sql query?

I have a table like:

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 |

All I want is to select most recent date of each vending_machine_id with a third field ( manual ) to have true/false (if there are both true and false realdings for that vending_machine_id, true (if there are only true manual readings), or false .

I have done this so much:

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

And it prints:

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

As you noticed, what I still don't know how to do is to have a single row with 543 vending_machine_id and that line to have at the end f/t . (because this id has both true and false manual reading types).

Is there any way I can accomplish this?

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

Is this what you want:

select vmrp.vending_machine_id, MAX(timestamp),
       bool_and(manual)
from vmrp.vending_machine_id
group by vmrp.vending_machine_id

Try:

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

SQLFiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM