2

Have three columns

ID  User     Quantity   Date
1    x        0       2016-01-01
2    x        2       2016-01-02
3    x        0       2016-01-03
4    x        0       2016-01-04
5    xx       0       2016-01-01
6    xx       2       2016-01-02
7    xx       0       2016-01-03
8    xx       8       2016-01-04
9    xx       0       2016-01-06
10   xx       0       2016-01-04

Now How do i get user wise first of the latest sequence of 0 entry for x user ID=3,xx ID=9.

Manoj
  • 191
  • 2
  • 3
  • 14

3 Answers3

1

It's a bit complex, because we need to find the last not 0 entry for a name. (I would naturally tend to sort by date, but you said ID is what to go for.)

   SELECT t1.name, max(t1.id) as check_id FROM table t1 WHERE quantity > 0 GROUP BY name

Now you can get the lowest number for each name that is higher than the given check_id:

SELECT name, min(t2.id) FROM table t2
JOIN (SELECT t1.name, max(t1.id) as check_id FROM table t1 WHERE quantity > 0 GROUP BY name) as a ON a.name=t2.name
WHERE t2.quantity = 0 AND t2.id > a.id
GROUP BY t2.name

There's one problem. It will exclude everyone with only 0 quantity. If this could happen you need another query with the following code (to get only 0 values)

SELECT name, min(id) as check_id, sum(quantity) as qty_sum FROM table
GROUP BY name
HAVING qty_sum = 0
fancyPants
  • 50,732
  • 33
  • 89
  • 96
Seb
  • 1,521
  • 1
  • 12
  • 19
0

As already mentioned, the first step is to identify the last dataset with a positive quantity by each user. The lowest ID of all following datasets would be what you seek. In other words, you need to look for MAX(ID) of all positive entries and apply MIN(ID) on all entries with a higher ID. In one query:

SELECT `User`, MIN(`ID`) FROM t `mainquery`
WHERE `ID` > (
  SELECT MAX(`ID`) FROM t `subquery`
  WHERE `Quantity` > 0 AND `mainquery`.`User` = `subquery`.`User`
  GROUP BY `User`
)
GROUP BY `User`

With the data from your example, this query returns:

User    MIN(`ID`)
x       3
xx      9

Test it here: http://sqlfiddle.com/#!9/3c487/1/0

friedemann_bach
  • 1,418
  • 14
  • 29
0

Try This:

SELECT t1.user,min(t1.id) as ID,quantity,date from tablename t1
JOIN
(SELECT MAX(id) as qid,user FROM tablename WHERE Quantity>0 GROUP BY user) t2
ON t2.user=t1.user
WHERE t1.id>t2.qid
AND t1.Quantity=0
GROUP BY t1.user
Nitin
  • 290
  • 2
  • 12