SQL Select to make a value appear only once

寵の児 提交于 2020-06-27 08:21:16

问题


For those that have been helping me along the way with this twitter-clone, thank you!! With your help, I've managed to get most things working and finally now to the last steps of the followers function.

Right now, I have a dataset with the following fields: username, tweet, date

An example of the data could look like:

Username    Tweet             Date
kenny       hi!               2011-10-07 19:07:00
stan        hello             2011-10-05 18:07:00
kenny       looks like rain   2011-10-05 17:07:00
stan        hello             2011-10-05 14:07:00
cartman     authoritay!       2010-10-05 14:07:00

And I've been wrestling with the SQL statement that would produce a data set in which each user appears only once with their latest tweet. So, based on the above, something that looks like this:

Username    Tweet             Date
kenny       hi!               2011-10-07 19:07:00
stan        hello             2011-10-05 18:07:00
cartman     authoritay!       2010-10-05 14:07:00

I've been googling sql searches and have tried variations of COUNT, DISTINCT, MAX, but to no avail. Any help would be greatly appreciated! Thank you!


回答1:


select d1.username, d1.tweet, d1.date from data d1 where d1.date = 
    (select max(d2.date) from data d2 where d1.username = d2.username)



回答2:


Would it not work just by

select distinct username, tweet, date order by date desc

(This is MSSQL syntax)

With new data in hand:

SELECT DISTINCT tweets.username, content, date from tweets 
WHERE user_id IN (
  SELECT users.id FROM users 
  INNER JOIN user_users ON users.id = user_users.followed_user_id 
WHERE user_users.user_id = 1) 
ORDER BY date desc



回答3:


SELECT f.*
FROM (
      SELECT Username, MAX(`Date`) as maxval
      FROM  table GROUP BY Username    
     ) AS x INNER JOIN table AS f
ON f.Username  = x.Username  AND f.`Date`= x.maxval


来源:https://stackoverflow.com/questions/7686049/sql-select-to-make-a-value-appear-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!