Resp.: need help in building a query

Поиск
Список
Период
Сортировка
От Osvaldo Kussama
Тема Resp.: need help in building a query
Дата
Msg-id 690707f60811071251w534d7aeej709f3a31233c0479@mail.gmail.com
обсуждение исходный текст
Ответ на Re: need help in building a query  ("Devil™ Dhuvader" <gibsosmat@gmail.com>)
Ответы Re: need help in building a query  ("Devil™ Dhuvader" <gibsosmat@gmail.com>)
Список pgsql-sql
2008/11/7, Devil™ Dhuvader <gibsosmat@gmail.com>:
> its like sum up entries of each user in order table backwards (i.e from last
> entry to the first) and find the entry that has sum > $500.
> If there is some user who didnt even make 500 till now in my shop return the
> first date of transaction/order.
>
> ex:
> Orders(order_id, user_id, amount_paid, create_timestamp)
> values:
> (1, 1, 100, 1)
> (2, 1, 300, 2)
> (3, 2, 100, 2)
> (4, 2, 100, 3)
> (5, 1, 100, 4)
> (6, 1, 200, 5)
> (7, 2, 150, 5)
>
> for user 1: the order_id = 2
> for user 2: the order_id = 3 (coz he couldnt make 500)
>


Try:

bdteste=# SELECT o1.user_id, o1.order_id, '>= 500' AS cond FROM Orders o1
bdteste-#  WHERE (SELECT sum(o2.amount_paid) FROM Orders o2 WHERE
o2.user_id = o1.user_id AND o2.order_id > o1.order_id) < 500 AND
bdteste-#        (SELECT sum(o2.amount_paid) FROM Orders o2 WHERE
o2.user_id = o1.user_id AND o2.order_id >= o1.order_id) >=500
bdteste-# UNION
bdteste-# SELECT user_id, min(order_id) AS "min order id", '< 500' AS
cond FROM Orders
bdteste-#  WHERE user_id IN (SELECT user_id FROM Orders GROUP BY
user_id HAVING sum(amount_paid) < 500)
bdteste-#  GROUP BY user_id;user_id | order_id |  cond
---------+----------+--------      1 |        2 | >= 500      2 |        3 | < 500

Osvaldo


В списке pgsql-sql по дате отправления:

Предыдущее
От: Tom Lane
Дата:
Сообщение: Re: Res: Finding all tables that have foreign keys referencing a table
Следующее
От: Frank Bax
Дата:
Сообщение: Re: need help in building a query