简体   繁体   中英

PostgreSQL: Need to perform Row operation

I'm new with PostgreSQL. I would like to perform a row operation on my table. For example consider this table output :

Record  | Accesories |    Used
Joy     | Laptop     |     500
Joy     | Android    |     270
Stuart  | Laptop     |     300
Stuart  | Android    |      25

I would like to display the name of "Record" for which Android usage is upto 10% of Laptop.IN this case its Joy who is using Android device upto 10% of Laptop. Mathematical calculation we did : (270/500)*100=54% . I want same operation to be done in my table. Table is having more than 1lac such record. Can someone help me for framing query for same. Thanks

select
    T1.Record
from Table1 as T1
    inner join Table1 as T2 on T2.Record = T1.Record
where
    T1.Accesories = 'Android' and T2.Accesories = 'Laptop' and
    (T1.Used::float / T2.Used * 100)::int > 10

Actually what's done here - we get all rows from Table1 where Accesories = 'Android' and then for each record we trying to find records where Record = Record from chosen row and Accesories = 'Laptop' (note that if Record, Accesories is not unique key for your table, you could end up with duplicate rows). After that, all you need it's just calculate value and filter out rows which're not satisfy condition (by adding this to where clause).

sql fiddle demo

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