Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9046469
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T11:40:01+00:00 2026-06-16T11:40:01+00:00

I’m trying to select only one row from each portal (the last one by

  • 0

I’m trying to select only one row from each portal (the last one by date) but I’m getting trouble with group by/distinct

Using this code, I can select only the portalId that I need, but without any data

Select relNews.PortalId
from news
left join relNews on relNews.NewsId= news.NewsId
group by relNews.PortalId

When I add one or more data columns like in this code, the select brings all the info, not only one for each portal

Select relNews.PortalId, news.NewsId
from news
left join relNews on relNews.NewsId= news.NewsId
group by relNews.PortalId, news.NewsId

I know that is a small trick that I’m missing here, but I just can’t remember what…

UPDATE

Lets make virtual tables for this example. The tables are news and relNews (I made them as short as possible here)

Table news

  • NewsId
  • Title
  • Description
  • Date

Table relNews

  • RelNewsId
  • NewsId
  • PortalId

NOTE:

  • relNews can have N registers of the same NewsId
  • I need to select the last register for each portalId (based on news.Date).

Lets say:

Table news

  • NewsId == 1
  • Title == ‘test’
  • Description == ‘test’
  • Date == ‘2013-01-01 00:00:00’

  • NewsId == 2

  • Title == ‘test2’
  • Description == ‘test2’
  • Date == ‘2013-01-01 03:00:00’

  • NewsId == 3

  • Title == ‘test3’
  • Description == ‘test3’
  • Date == ‘2013-01-02 00:00:00’

Table relNews

  • RelNewsId == 1
  • NewsId == 1
  • PortalId == 1

  • RelNewsId == 2

  • NewsId == 1
  • PortalId == 2

  • RelNewsId == 3

  • NewsId == 2
  • PortalId == 1

  • RelNewsId == 4

  • NewsId == 3
  • PortalId == 3

This data should bring:

RelNewsId == 2; RelNewsId == 3; RelNewsId == 4;


I can get the result that I want with this code:

Select top 1 relNews.PortalId, news.NewsId, news.date
from news
left join relNews on relNews.NewsId= news.NewsId
where relNews.PortalId == 1
group by relNews.PortalId, news.NewsId
order by news.date desc
UNION
Select top 1 relNews.PortalId, news.NewsId, news.date
from news
left join relNews on relNews.NewsId= news.NewsId
where relNews.PortalId == 2
group by relNews.PortalId, news.NewsId
order by news.date desc
UNION
Select top 1 relNews.PortalId, news.NewsId, news.date
from news
left join relNews on relNews.NewsId= news.NewsId
where relNews.PortalId == 3
group by relNews.PortalId, news.NewsId
order by news.date desc

Then I get all 3 results.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T11:40:02+00:00Added an answer on June 16, 2026 at 11:40 am

    You have to provide some way of indicating which one of the news rows you want, when there could be multiple for one relNews row. As you’ve discovered, the moment you GROUP BY a column that can have many values for each parent, then you get multiple rows. There are several ways to do this. Since you are using SQL Server 2008 you have several options.

    1. CROSS/OUTER APPLY – change the OUTER APPLY to CROSS APPLY if you want to exclude relNews rows when there is no matching News row.

      SELECT
         R.Whatever,
         N.Whatever
      FROM
         dbo.relNews R
         OUTER APPLY (
            SELECT TOP 1 *
            FROM dbo.News N
            WHERE R.newsId = N.Id
            ORDER BY N.newsDate DESC
         ) N
      
    2. Row_Number()

      SELECT
         R.Whatever,
         N.Whatever
      FROM
         dbo.RelNews R
         LEFT JOIN
            (
               SELECT
                  *,
                  Selector = Row_Number()
                     OVER (PARTITION BY N.Id ORDER BY N.newsDate DESC),
               FROM dbo.News N
            ) N ON R.newsId = N.Id
            AND N.Selector = 1
      
    3. Aggregate – this is more complicated than it may seem to require, but I assumed that newsDate is NOT unique per newsID. If it is unique then it’s simpler. This version works in SQL 2000. This is also probably the worst-performing query of all the options I am providing. Note that UniqueColumn is any column that has guaranteed unique values per newsID and can be used to select among ties for newsDate.

      SELECT
         R.Whatever,
         N.Whatever
      FROM
         dbo.RelNews R
         LEFT JOIN (
            dbo.News N
            INNER JOIN (
               SELECT N.Id, MaxUnique = Max(UniqueColumn)
               FROM
                  dbo.News N
                  INNER JOIN (
                     SELECT N.Id, MaxDate = Max(N.newsDate)
                     FROM dbo.News N
                     GROUP BY N.Id
                  ) X ON N.Id = X.Id
                  AND N.newsDate = X.MaxDate
               GROUP BY N.Id
            ) X ON N.Id = X.Id
            AND X.UniqueColumn = X.MaxUnique
         ) ON R.newsId = N.Id
      

      If newsDate is truly unique per news.Id then here is that query:

      SELECT
         R.Whatever,
         N.Whatever
      FROM
         dbo.RelNews R
         LEFT JOIN (
            dbo.News N
            INNER JOIN (
               SELECT N.Id, MaxDate = Max(N.newsDate)
               FROM dbo.News N
               GROUP BY N.Id
            ) X ON N.Id = X.Id
            AND N.newsDate = X.MaxDate
         ) ON R.newsId = N.Id
      
    4. Subquery – with the problem that you can only pull one column at a time but works in SQL 2000, and should perform well with proper indexes. For multiple columns may perform badly as it may do a separate query for each one.

      SELECT
         R.Whatever,
         NWhatever = (
            SELECT TOP 1 N.Whatever
            FROM dbo.News N
            WHERE R.newsId = N.Id
            ORDER BY N.newsDate DESC
         )
      FROM
         dbo.relNews R
      
    5. Subquery in the ON clause – probably the best query for SQL 2000 if you’re going to pull multiple columns. Has to hit the News table twice, but with proper indexes it shouldn’t be so bad. Note that UniqueColumn is any column that has guaranteed unique values per newsID and can be used to select among ties for newsDate.

      SELECT
         R.Whatever,
         N.Whatever
      FROM
         dbo.relNews R
         LEFT JOIN dbo.News N
            ON R.newsId = N.Id
               -- above condition not absolutely required logically,
               -- but definitely for indexes
            AND N.UniqueColumn = (
               SELECT TOP 1 N.UniqueColumn
               FROM dbo.News N
               WHERE R.newsId = N.Id
               ORDER BY N.newsDate DESC
            )
      
    6. Logical-Last – another possibly good performer for SQL 2000. This is the same logical query as fo_x86 but expressed a little differently.

      SELECT
         R.Whatever,
         N.Whatever
      FROM
         dbo.relNews R
         LEFT JOIN dbo.News N
            ON R.newsId = N.Id
            AND NOT EXISTS (
               SELECT *
               FROM dbo.News X
               WHERE
                  N.Id = X.Id
                  AND (
                     N.newsDate < X.newsDate
                     OR (
                        N.newsDate = X.newsDate
                        AND N.UniqueColumn < X.UniqueColumn
                     )
                  )
            )
      

    Option #1 is probably the best for you in the database version you’re using.

    One last note: As always, testing is required. The performance of all these different queries will depend on a lot of factors: the pattern of your data (many dates for each news item or few), the exact indexes, how wide the tables are, and whether you add extra conditions (for example, the row number one as I suggested will not do so well if your conditions on the outer relNews table return only a few rows). If you find that one query is not providing satisfactory execution times, try a different one.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to select an H1 element which is the second-child in its group
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to understand how to use SyndicationItem to display feed which is
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to render a haml file in a javascript response like so:
I am using the SimpleRSS gem to parse a WordPress RSS feed. The only

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.