• 1

[SQL] Select multiple columns with only one distinct column


Question

How do you select multiple columns from a table while ensuring that one specific column doesn't contain duplicate values?

SELECT DISTINCT col1,col2,col3,col4 from table

This doesn't work, because DISTINCT here applies to all columns so columns as a whole are distinct. But I want a single column to have distinct values.

I'm using SQL Server. :)

6 answers to this question

Recommended Posts

  • 0

You're looking for GROUP BY. If you wanted to only have the value for col1 show up once in the dataset:

SELECT col1,col2,col3,col4 from table GROUP BY col1

Note that this will compact all the results that would have been display into one row. So you'll end up having to use sums or some other aggregate function to display the correct values if you can expect a different value in a row each time it shows up. Otherwise it will just pick the value from the first row.

  • 0

Thanks for your answer, it actually does serve my purpose. :)

This is the query I ran:

SELECT col1,max(col2), max(col3), max(col4) from table GROUP BY col1

Max functions used here don't mean much, they'er just there to pick the biggest value of the column in the row set.

As I said, in this case it serves my purpose. But what if there were, let's say 4 or more rows with a common col1 value, and you wanted to retrieve columns of some specific middle row among the grouped rows; How would you go about that?

I'm thinking cursors can be one way to do that, right?

  • 0

Thanks for your answer, it actually does serve my purpose. :)

This is the query I ran:

SELECT col1,max(col2), max(col3), max(col4) from table GROUP BY col1

Max functions used here don't mean much, they'er just there to pick the biggest value of the column in the row set.

As I said, in this case it serves my purpose. But what if there were, let's say 4 or more rows with a common col1 value, and you wanted to retrieve columns of some specific middle row among the grouped rows; How would you go about that?

I'm thinking cursors can be one way to do that, right?

I believe you could (SQL Server is not my strongest database skill), but if you can it would be better if you can weed out the row you want using the WHERE clause of the SQL statement.

  • 0

It sounds like you need to do something like the following:

select
* --should specify your specific columns
from table1 t1
inner join 
(select DISTINCT distinctColumn from table) t2
on t1.col = t2.distinctColumn

This code should get your distinct column and then join on it from another (or even the same) table.

  • 0

It sounds like you need to do something like the following:

select
* --should specify your specific columns
from table1 t1
inner join 
(select DISTINCT distinctColumn from table) t2
on t1.col = t2.distinctColumn

This code should get your distinct column and then join on it from another (or even the same) table.

No, doesn't work. It returns duplicate rows.

It doesn't matter tho, as my problem is solved, even ignoring the @kjordan2001's answer. I just needed to omit those non-duplicate valued columns from the select list of a distinct clause, which were trivial anyways. The result set would then only include entirely distinct rows. And FYI, the table in question is named Customer and is part of the AdventureWorks2008R2 sample databases.

Thanks for answers though. :)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Mate, you’re looking to spend about $100 - what are you expecting. The A series is not the high end model, no - but “trash” is nonsense. The sort of thing that idiots who only buy the highest end models say as some sort of self validation. They will do everything you need of them.
    • Stack Overflow is launching a version of itself for AI agents by David Uzondu Stack Overflow has announced Stack Overflow for Agents, a platform that traditionally hosts crowdsourced programming solutions for human developers, but now serves autonomous software agents. Basically, Stack Overflow's argument is that the rapid democratization of building software has exposed a major vulnerability. Agents operate in isolation, creating an Ephemeral Intelligence Gap where they waste valuable tokens on something another agent halfway across the world has already solved. That's why, according to the company, a shared, real-time knowledge repository is needed. Stack Overflow for Agents is currently in beta, running as an API-first knowledge exchange where humans review what agents publish. To prevent hallucination issues and keep the database clean, the platform uses a multi-agent verification loop to check code quality. This system forces agents to query the corpus first to locate validated answers rather than running expensive code-generation scripts. To ensure trust, Stack Overflow connects agent contributions directly to the human developer's established reputation through single sign-on credentials. The agents can interact with three distinct post types. One option, Questions, documents unsolved bugs, while "Today I Learned" posts record debugging traces. Blueprints round out the selection by storing reusable design patterns. If an enterprise wants to keep proprietary data private, the Stack Internal platform allows the organization to run the assistant behind its own firewall. Before the massive rise of LLMs, which tanked its traffic by about 50% over the last couple of years, Stack Overflow was the go-to website for millions of programmers seeking coding solutions. Some argue that another reason why the website sort of fell off stems from its notoriously hostile (and condescending) community that frequently closed basic questions and alienated beginners with strict gatekeeping. In order to avoid getting eaten by AI, Stack Overflow has tried several things. When volunteer moderators banned AI-generated content in 2023 to protect data quality, corporate leaders tried to limit those restrictions, prompting the volunteers to stage a massive site-wide strike. Since then, the developer portal has signed major deals with tech companies like Google to bring Stack Overflow data directly into Gemini models and Google Cloud console. A similar deal with OpenAI in 2024 sparked an uproar, leading some users to delete old answers in protest. The company swiftly suspended those accounts to protect the database. It has also experimented with OverflowAI, an AI-powered conversational search tool designed to pull together answers from multiple threads.
    • There are two options for smartphone platforms so consumers don't have much of a choice there. The EU is not making any decisions for customers they just want them to have options if they so choose. I am not sure why you would be for closed platforms. The big tech companies already have so much power and money while are relatively unregulated in the US which is why they run into so much trouble in the EU.
    • Hello, I am using a Moto G Stylus (2025) and happy with it.  I don't know how well the model works on Twigby's network (it looks like they are an MVNO of Verizon).  It looks like they have a BYOD plan, though, so as long as you find a device that works on their network you should be okay.   Regards,   Aryeh Goretsky 
  • Recent Achievements

    • First Post
      StaticMatrix earned a badge
      First Post
    • Week One Done
      StaticMatrix earned a badge
      Week One Done
    • Rookie
      lamborghiniv10 went up a rank
      Rookie
    • One Month Later
      pinnclepd earned a badge
      One Month Later
    • First Post
      X-No-file earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      533
    2. 2
      PsYcHoKiLLa
      209
    3. 3
      +Edouard
      151
    4. 4
      Steven P.
      100
    5. 5
      ATLien_0
      84
  • Tell a friend

    Love Neowin? Tell a friend!