简体   繁体   中英

SQL query returns wrong result set

I have this table:

columns:
Id  product_id name status update_date

1   1   prod1   bought  2016-04-20 10:10:10
2   1   prod1   sold    2016-04-22 12:25:00
3   1   prod1   sold    2016-06-03 09:42:15

I wanna execute this query:

select id,name,status,max(update_date) from product group by name,status;

I get:

1   prod1   bought  2016-04-20 10:10:10
2   prod1   sold    2016-06-03 09:42:15

For the second row in the result set, I have to get:

3   prod1   sold    2016-06-03 09:42:15

and not: 2 prod1 sold 2016-06-03 09:42:15 !

Try this;)

select id,name,status,update_date from product
where (name, status, update_date) in (
    select name,status,max(update_date) from product
    group by name,status
)

Or

select t1.id, t1.name, t1.status, t1.update_date
from product t1
inner join (
    select name,status,max(update_date) as update_date from product
    group by name,status
) t2 on t1.name = t2.name and t1.status = t2.status and t1.update_date = t2.update_date

Simple Query, try this

select product_id,name,status,MAX(update_date) as date 
from product group by product_id,name,status
select distinct A.id, A.name, A.status, A.update_date 
  from product A,
(select `name`,status,max(update_date) update_date
   from product
  group by `name`, status) B
where A.name=B.name and A.status=b.status and a.update_date=b.update_date

Explanations: the distinct is used in case you have 2 exact update_dates

SQLFiddle : http://www.sqlfiddle.com/#!9/b8218/2

I have tried the query and it is working.

CREATE TABLE  ##product(
Id  INT,
product_id INT,
name NVARCHAR(100),
 status NVARCHAR(100),
 update_date DATETIME
 );

INSERT INTO ##product
 VALUES
 (1,   1,   'prod1',   'bought',  '2016-04-20 10:10:10'),
( 2,   1,   'prod1',   'sold',    '2016-04-22 12:25:00'),
 (3,   1,  'prod1' ,  'sold',    '2016-06-03 09:42:15')

 SELECT id, name, status, update_date FROM ##product WHERE update_date IN 
 (
 SELECT MAX(update_date) FROM ##product GROUP BY name, status
 )


 DROP TABLE ##product 

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