I have a problem with SQL query, and I will try to explain what I want to do. This is my query which returns some result rows.
SELECT
sck.sckid,
sck.prid,
sck.paid,
sck.sckcen,
sum(scd.scdkiek) as count_of_goods,
min(scn.scndat) as `date`
FROM sck
INNER JOIN scd ON scd.sckid = sck.sckid
INNER JOIN scn ON scn.scnid = scd.scnid
INNER JOIN sandeliai ON sandeliai.paid = sck.paid
WHERE sck.prid = 1376 GROUP BY sckid
And this query returns "Table 1" of results:
Table 1:
sckid | prid | sckcen | count_of_goods | date |
123 | 1376 | 10009 | 0 | 2012-12-31 |
124 | 1376 | 10007 | 15 | 2013-01-25 |
125 | 1376 | 10005 | 0 | 2013-02-13 |
126 | 1376 | 10000 | 18 | 2013-03-15 |
But I need just one row with all data grouped by prid
, and I wrote this query:
SELECT
sck.sckid,
sck.prid,
sck.paid,
sck.sckcen,
sum(scd.scdkiek) as count_of_goods,
min(scn.scndat) as `date`
FROM sck
INNER JOIN scd ON scd.sckid = sck.sckid
INNER JOIN scn ON scn.scnid = scd.scnid
INNER JOIN sandeliai ON sandeliai.paid = sck.paid
WHERE sck.prid = 1376 GROUP BY prid
Then I get one row with this data in table:
Table 2:
sckid | prid | sckcen | count_of_goods | date |
123 | 1376 | 10009 | 23 | 2012-12-31 |
It's seems all correct, but in date
field I need to return most earlier date from table one, which have count_of_goods > 0, so for me need this result:
Table 3:
sckid | prid | sckcen | count_of_goods | date |
123 | 1376 | 10009 | 23 | 2013-01-25 |
So any ideas how can I get result like in Table 3?