简体   繁体   中英

How to compare results from the same timestamp in SQL(sqlite)?

I've got a simple table in sqlite which looks like this:

dt                  | ab | price
-----------------------------
2014-01-06 21:57:00 | a  | 86
2014-01-06 21:57:00 | b  | 89
2014-01-06 21:58:00 | b  | 84
2014-01-06 21:58:00 | a  | 82
2014-01-06 21:59:00 | a  | 82
2014-01-06 21:59:00 | b  | 66

So for every datetime I've got a price from 'a' and from 'b'. I now want to get a list in which I can easily compare the prices like this:

dt                  | price of a | price of b
----------------------------------------------
2014-01-06 21:57:00 | 86         | 89
2014-01-06 21:58:00 | 82         | 84
2014-01-06 21:59:00 | 82         | 66

I tried this: SELECT dt, price FROM prices GROUP BY dt; , but to no avail. I understand why ths doesn't work, but I don't really know how to do it properly. I guess I need to use a join or something, but I'm not so proficient in SQL.

Could anybody give me a tip on how I would be able to do this?

You want conditional aggregation:

SELECT dt,
       max(case when ab = 'a' then price end) as a_price,
       max(case when ab = 'b' then price end) as b_price
FROM prices
GROUP BY dt;

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