Question: I need to open a .csv file and instantly save it with the same name (overwrite it) using a .bat. 

This may sound stupid but it is the easiest way that I've found to change that .csv file codification (from ANSI to UTF-8).

If I type notepad file-name.csv it opens the .csv file, but how do I save it now?

Answer: 
Try it out. Not tested 

```
SELECT t1.ID, count(*) FROM table t1 
WHERE t1.StatusDate >= (SELECT MAX(t2.StatusDate) FROM table t2 
                     WHERE t1.ID = t2.ID AND t2.Status = 'P') 
GROUP BY t1.ID

```
One option is to use a JOIN and COUNT rows which have a lower statusdate value, like this:

```
SELECT t1.id, SUM(CASE WHEN t1.statusdate > t2.statusdate THEN 1 ELSE 0 END) AS mycount
FROM t t1 JOIN (
  SELECT id, MIN(statusdate) statusdate
  FROM t
  WHERE status = 'P'
  GROUP BY id
  ) t2
ON t1.id = t2.id 
GROUP BY t1.id

```

Working Demo: <http://sqlfiddle.com/#!2/d9d91/2>