选择整个表但特定列中的唯一值
请帮我解决一下我工作中遇到的问题。我正在使用 SQL Server,并且我知道使用游标可以实现此目的,但我很确定有一种方法可以使用 SQL 中的简单查询来实现此目的,但我的大脑不想这样做打开。让我用一个例子来解释我的问题。
我有一个像这样的表:
postedby | date | comment |
1 | 01.01.2012 | sth sth |
2 | 01.01.2012 | sth sth |
3 | 01.01.2012 | sth sth |
2 | 01.01.2012 | sth sth |
3 | 02.01.2012 | sth sth |
2 | 03.01.2012 | sth sth |
2 | 05.01.2012 | sth sth |
我想要完成的是获取所有帖子,但每个用户都有一个帖子(发布者列),日期必须是最新的,当然还要显示评论。
我尝试过这样做:
Select distinct postedby, date, comment
但没有成功,因为我了解每一列都有不同的工作,所以如果在两行中,postedby 相同但注释不同,它将把它视为
我尝试过的不同之处:
选择Postedby, date,comment group by postsby
(不用理会 from 子句) 给我错误或聚合,所以我尝试了 select postsby,min(date) group by postsby
- 当然可以,但我无法得到评论。
我应该以某种方式使用聚合查询吗?或者我错过了什么?
Please help me with an issue that I have come across during work. I'm working with SQL Server, and I'm aware that using cursors I could achieve this, but I'm pretty sure that there is a way of doing it using simple query in SQL, but my brain bulb doesn't want to turn on. Let me explain my issue with an example.
I have got a table like this:
postedby | date | comment |
1 | 01.01.2012 | sth sth |
2 | 01.01.2012 | sth sth |
3 | 01.01.2012 | sth sth |
2 | 01.01.2012 | sth sth |
3 | 02.01.2012 | sth sth |
2 | 03.01.2012 | sth sth |
2 | 05.01.2012 | sth sth |
What I want to accomplish is get all the posts but one for every user (postedby column), the date must be the latest and of course show the comment.
I have tried doing:
Select distinct postedby, date, comment
but didn't work, as I understand distinct works for every column, so if in 2 rows postedby is the same but comment is different it will treat it as distincts
I have tried doing:
Select postedby,date,comment group by postedby
(don't bother about the from clause)
giving me the error or aggregation, so I triedselect postedby,min(date) group by postedby
- of course works, but I can't get the comment.
Should I use in some way aggregated queries? Or what am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来今天是 RowNumber 函数日!
如果您需要的只是每个帖子的最新日期和评论:
Looks like today is the RowNumber function day!!
If all you needed is the latest date and comment for each post:
您尝试了
分钟(日期)
。它将返回唯一值的最小日期。您尝试过max(date)
吗?这样做会更好。最大日期始终返回最新日期。You tried
min(date)
. It will return min date of unique value. Have you triedmax(date)
? It will be better for that. The max date always return the latest date.