Use DISTINCT with two fields to return one record

I am using OleDB with a SELECT DISTINCT query that is used in C# code to populate a DataGridViewComboBox.  The queried table has two fields: ID and Description. The ID field values are unique. Descriptions may be duplicated. The DataSource of my DataGridViewComboBox
is ListBoxItems which is a ListBox that is populated from a table. The ValueMember is ID and the DisplayMember is Description.  A sample table might look like this:
ID    Description
 1     Blue
 2     Blue
 3     Red
 4     Blue
I want my query to return two records; one for the Red description and only one for the Blue description.  I don't care which Blue description it returns, but I do need the corresponding ID for the selected Blue record and the ID value for the Red record. 
Using SELECT DISTINCT ID, Description FROM... would give me four records instead of two.  How can I return only two records in this scenario?
Rob E.

Using window function:
create table #temp
ID int,
description varchar(20),
insert into #temp Values(1,'blue')
insert into #temp Values(2,'blue')
insert into #temp Values(3,'red')
insert into #temp Values(4,'blue')
;WITH CTE AS (select RN=ROW_NUMBER() OVER (PARTITION BY description ORDER BY newid() ),
ID,description from #temp)
SELECT ID, description from CTE
WHERE RN = 1;
ID description
4 blue
3 red
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

Similar Messages

  • Using imessage with two mobile numbers  on one iphone?

    hi is it possible to use two mobile numbers on imessage ,   with only one iphone?
    i have an old phone , and an iphone, but would like to be able to use receive imessages on the iphone  , using the two numbers,  is this possible?
    thanks

    no

  • Using Berkeley With Two Different Environment Simultaneously

    I am trying to use Berkeley with two different environment simultaneously in one program. But I am getting an error message of Databases left open. The first environment close with no error but the 2nd environment, having an error like this,
    Exception in thread "main" java.lang.IllegalStateException: Unclosed Database: element_primary_key_index\\192.168.150.211\glassfish3\Berkeley\environment\Testing11
    Unclosed Database: class_catalog\\192.168.150.211\glassfish3\Berkeley\environment\Testing11
    Unclosed Database: element_database\\192.168.150.211\glassfish3\Berkeley\environment\Testing11
    Databases left open: 3
         at com.sleepycat.je.Environment.close(Environment.java:383)
         at com.svi.tools.gfs3v10domain.database.GFS3v10ReadWriteDatabase.closeUpload(GFS3v10ReadWriteDatabase.java:155)
         at com.svi.tools.gfs3v10domain.GFS3v10Domain.closeReadWrite(GFS3v10Domain.java:160)
         at com.svi.tools.gfs3v10.util.GFS3v10UploadUtil.closeUpload(GFS3v10UploadUtil.java:97)
         at com.svi.tools.gfs3v10.GFS3v10.closeUpload(GFS3v10.java:115)
         at com.svi.tools.gfs3v10uploader.util.Uploader.uploadFiles(Uploader.java:89)
         at com.svi.tools.gfs3v10uploader.GFS3v10Uploader.mainMethod(GFS3v10Uploader.java:109)
         at com.svi.tools.gfs3v10uploader.GFS3v10Uploader.main(GFS3v10Uploader.java:52)
    Please someone help me with my problem. Thanks in advance.

    Hi Mark,
    Here is my sample program for the problem:
    import java.io.File;
    import com.sleepycat.bind.serial.StoredClassCatalog;
    import com.sleepycat.je.Database;
    import com.sleepycat.je.DatabaseConfig;
    import com.sleepycat.je.Environment;
    import com.sleepycat.je.EnvironmentConfig;
    import com.sleepycat.je.EnvironmentLockedException;
    import com.sleepycat.je.SecondaryConfig;
    import com.svi.tools.gfs3v10domain.objects.GFS3v10DomainElementData;
    import com.svi.tools.gfs3v10domain.objects.GFS3v10DomainElementKey;
    import com.svi.tools.gfs3v10domain.views.utils.ElementByPrimaryKeyCreator;
    * Read Write Database used for every thing else.
    public class MethodsSample implements GFS3v10Database {
         * Environment where the Database resides.
         private Environment environment = null;
         private boolean isClose = false;
         String environmentString;
         * Class Catalog for Stored Classes.
         private static StoredClassCatalog classCatalog;
         * Element Database.
         private static Database elementDatabase;
         * Element Database by Primary Key.
         private static Database elementByPrimaryKeyDatabase;
         private static Database catalogDatabase;
         * Default Constructor.
         public MethodsSample() {
    * Alternate Constructor.
    * @param homeDirectory Location where the Database is Located.
    public MethodsSample(String homeDirectory) {
         environmentString = homeDirectory;
         openEnvironment(homeDirectory);
         openDatabase();
    @Override
         * Opens the Read Write Database.
         * @param homeDirectory Location where the Database is Located.
    public void openEnvironment(String homeDirectory) {
         EnvironmentConfig environmentConfig = new EnvironmentConfig();
    environmentConfig.setTransactional(true);
    environmentConfig.setAllowCreate(true);
    environmentConfig.setDurability(DURABILITY);
    while (environment == null) {
         try {
              environment = new Environment(new File(homeDirectory), environmentConfig);
         } catch(EnvironmentLockedException ele) {
              try {
                             Thread.sleep(500);
                        } catch (InterruptedException e) {
    @Override
         * Opens the Database.
    public void openDatabase() {
         DatabaseConfig databaseConfig = new DatabaseConfig();
         databaseConfig.setDeferredWrite(true);
    databaseConfig.setAllowCreate(true);
    catalogDatabase = environment.openDatabase(null, CLASS_CATALOG + environmentString, databaseConfig);
    classCatalog = new StoredClassCatalog(catalogDatabase);
    elementDatabase = environment.openDatabase(null, ELEMENT_DATABASE + environmentString, databaseConfig);
    SecondaryConfig secondaryConfig = new SecondaryConfig();
    secondaryConfig.setDeferredWrite(true);
    secondaryConfig.setAllowCreate(true);
    secondaryConfig.setSortedDuplicates(true);
    secondaryConfig.setKeyCreator(new ElementByPrimaryKeyCreator(classCatalog, GFS3v10DomainElementKey.class, GFS3v10DomainElementData.class, String.class));
    elementByPrimaryKeyDatabase = environment.openSecondaryDatabase(null, ELEMENT_PRIMARY_KEY_INDEX + environmentString, elementDatabase, secondaryConfig);
    @Override
         * Gets the Environment.
         * @return Environment.
    public Environment getEnvironment() {
         return environment;
    @Override
         * Gets the Class Catalog.
         * @return Class Catalog.
    public StoredClassCatalog getClassCatalog() {
         return classCatalog;
    @Override
         * Gets Element Database.
         * @return Element Database.
    public Database getElementDatabase() {
         return elementDatabase;
    @Override
         * Gets Element By Primary Key Database.
         * @return Element By Primary Key Database.
    public Database getElementByPrimaryKeyDatabase() {
         return elementByPrimaryKeyDatabase;
    @Override
         * Closes Database and then Environment.
    public void closeUpload() {
         System.out.println("1st Jar environment closing = " + environmentString);
         elementByPrimaryKeyDatabase.close();
         elementDatabase.close();
         classCatalog.close();
         catalogDatabase.close();
         environment.close();
         isClose = true;
    public Boolean isClose() {
         return isClose;
         @Override
         public void closeOthers() {
    for the Main:
    public class sample {
         public static void main(String[] args) {
              String environment1 = "\\\\192.168.160.184\\glassfish\\berkeley\\environment\\home\\Multiple\\Testing11";
              String environment2 = "\\\\192.168.150.211\\glassfish3\\Berkeley\\environment\\Testing11";
              openCloseEnvironment(environment1, environment2);
         public static void openCloseEnvironment(String environment1, String environment2) {
              MethodsSample forEnvironment1 = new MethodsSample(environment1); //Opens the Databases
              MethodsSample forEnvironment2 = new MethodsSample(environment2); //Opens the Databases
              forEnvironment1.closeUpload();
              forEnvironment2.closeUpload();
    // same error happens no matter what sequence for closing
    Thank you.

  • Is there a cable with two Apple connections and one USB connection?

    Is there a cable with two Apple connections and one USB connection?

    it would be possible without damage to the phones if only the charging pins was used
    but it would mean the 2 phones would charge 1/2 as fast as normally

  • Is possible to take the Infopath form with two repeat section in one SharePoint list

    Is possible to take the Infopath form  with two repeat section in one Sharepoint list 
    Take two repeat section and put them one bellow to other one in a SP list.
    The motive is that the first repeat section is based in account own by the requestor and the second repeat section is when the requestor is doing backup time for some one else where need to log the amount of time that spend in the peer account.
    I have basic logic in the form when requestor said Are you doing backup for some else? and press YES it is be able to use the second repeat section.
     Le me know how much pain full is going tobe or not..
    –Q1: Is possible to do this ?  With codeless or not
    –Q2:What steps I need to do to accomplish this?  feasible or not
    the following picture give a better idea of what I am looking to accomplish:
    CRISTINA&amp MICROSOFT Forum

    Hi,
    Thank you for your question. I am trying to involve someone familiar with this topic to further look at this issue. There might be some time delay. Appreciate your patience. Thank you for your understanding and support.
    Thanks,
    Linda Li
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Linda Li
    TechNet Community Support

  • Integrtion Scenario using BPM with two sender and multiple receiver

    integrtion Scenario using BPM with two sender and multiple receiver
    How many Application Components are required?

    Hi Vinod,
    1) In integration repository you can have one or many software components it depends on your landscape orchestration
    2) In integration direcory you need at least one service for bpm and one or many for each system in your bpm
    also each connection between systems and bpm must have receiver determination and so on.
    Advice: Please treat BPM as a separate system.
    best,
    Wojciech

  • Adding a custom tab in Purchase Order with two fields - ME21N

    Hello Experts,
    My requirement is to add a custom tab with two fields in purchase order at header level.
    The BADI ME_PROCESS_PO_CUST is alreday implemented previously as there was one custom tab added previously in header.
    The structure  CI_EKKODB already have the custom fields for the enhancement done earlier.
    Now to add my additional tab how should i proceed ....should i put my additional fields in the same structure and write my code in same BADI.....will there be any impact on already done enhanecement.
    Please suggest in achieving this functionality.
    Thanks,
    Naveen

    Hi,
    Check this [wiki|http://wiki.sdn.sap.com/wiki/display/ABAP/DetailedexplanationaboutBADIandthewaystofindtheBADIwithanexample%28ME23n+transaction%29], it tells you how to do with an example for item data.
    Regards,
    Eduardo

  • Using iPhone with two computers

    Home PC - MacBook Pro
    Work PC - Windows
    both running iTunes 7.7
    My music is on my home Mac and I manually create playlists, add music etc.
    With my 3G Nano, I can connect and listen to songs on my iPod from my work PC. I can't seem to do this with my iPhone - my PC sees the iPhone but all of the music is greyed out and cannot be selected.
    Is it a limitation of the iPhone that I cannot use it with two computers in this way, or is it a configuration issue?
    I would prefer not to have to buy a set of external speakers just to use my iPhone to play music at work.
    thanks
    Shane

    Actually, there are several articles on the web about the fact that you CAN
    synch the itunes with two computers. Music, Video, and Ringtones can be done from one computer, and Mail, Contacts, etc. can be done from a second computer.
    Just do a Yahoo search on "synching iPhone with two computers."
    If you are trying to do music from two computers, you are right, that will not work. There is a program, which I think the Yahoo search above will also uncover that allows you to do a "swap," where you can have the songs from one computer show up on the iPhone, and when you swap, the songs from the other computer show up. I am not sure if this utility survived the upgrage to version 2.0 of the softweare.
    cheers,
    Ray

  • I have one account, but use it as two for years.  One is home, one is work.  Recently we upgraded to Windows 7 at work and a new email system.  Now I can't download music at work; work tech support can't help but said to use my work email address. Failure

    I have one account, but use it as two for years.  One is home, one is work.  Recently we upgraded to Windows 7 at work and a new email system.  Now I can't download music at work; work tech support can't help but said to use my work email address. Failure.
    Could it be a new work firewall associated with the upgrades?  How can I resolve this?

    I have one account, but use it as two for years.  One is home, one is work.  Recently we upgraded to Windows 7 at work and a new email system.  Now I can't download music at work; work tech support can't help but said to use my work email address. Failure.
    Could it be a new work firewall associated with the upgrades?  How can I resolve this?

  • Mac Pro with two graphic card each one with two dvi output, can I extend deskop to three outputs?

    Mac Pro with two graphic card each one with two dvi output, can I extend deskop to three outputs?

    MAC OS 10.7.4  3.2GHz Quad-Core Intel Xeon processors, 12GB  of 800MHz DDR2 and 2 ATI Radeon HD 2600 XT 256MB (two dual-link DVI ports) . The problem is, I woul like to use one output as main and the three others as secondary or extended desktop but the system don't allow me use two diferent video cards this way.

  • I live in a home with two other people, and one housemate tried to sync up his content from iTunes and iCloud onto another housemate's new iPad. the iTunes library only contains my content. is there any way to retrieve the there person's iCloud?

    i live in a home with two other people, and one housemate tried to sync up his content from iTunes and iCloud onto another housemate's new iPad. the iTunes library only contains my content. is there any way to retrieve the other person's iCloud? Can they go out of my account? Their content is saved on their iPads, but can another iCloud be on the same home computer?

    The syncing of music is one way, computer to phone. See this helpful document from a fellow user. Credit goes to the author.
    https://discussions.apple.com/docs/DOC-3141

  • Generic delta   using function module with two fields  AEDAT AND ERDAT

    Hi,
        i have scenario that i have to create a generic data source  having delta using funcation module and the delta speci fields are AEDAT AND ERDAT . Is there possibility with out using these two fields ( i mean AEDAT AND ERDAT)  in the extract structure can i create the data source . and provide sample code for me . it is very urgent.
    waiting for the reply,
    sri.c

    Hi Sri,
    here some coding, I hope this helps!
    first, get the delta-field
          LOOP AT s_s_if-t_select INTO l_s_select.
            CASE l_s_select-fieldnm.
              WHEN 'ZDATE'.
                MOVE-CORRESPONDING l_s_select TO r_date.
                IF r_date-high IS INITIAL OR r_date-high = space.
                  r_date-high = '9991231'.
                ENDIF.
                APPEND r_date.
            ENDCASE.
          ENDLOOP.
    Cursor öffnen
          OPEN CURSOR WITH HOLD s_cursor FOR
          SELECT * FROM
          WHERE  ....
          AND    erdat in r_date
          AND    aedat IN r_date.
          FETCH NEXT CURSOR s_cursor INTO CORRESPONDING FIELDS OF table e_t_data package size s_s_if-maxsize.
    regards
    Siggi
    PS: Note that this coding only works for a very straight forward extraction.
    Message was edited by: Siegfried Szameitat

  • I was setting up my Airport and thought the first set up did not go through, so I set up again and I ended up with two accounts instead of one.  How can I manage to have only one account now? Thanks for the help.

    I was setting up my Airport and thought the first set up dod not go through, then I set up again and ended up with two wireless accounts.  I use it for the prointer and the iPad, and I can see both accounts in the iPad.  How do I get rid of one account?  Thanks for the help!

    me.com accounts can be used for iCloud.  See the FAQ section in:
    <http://support.apple.com/kb/ht4895>
    but it may be too late if you have already created a new AppleID.
    A few years ago Apple said they were working on allowing account merging, but it never happened (maybe objections from copyright holders).

  • Using itunes with two users

    How can my wife and I use iTunes on one pc with two separate i-devices? And how can she move her library to another computer?
    Regards
    Mike

    iTunes: How to move [or copy] your music to a new computer [or another drive] - http://support.apple.com/kb/HT4527
    Quick answer if you let iTunes manage your music:  Copy the entire iTunes folder (and in doing so all its subfolders and files) intact to the other drive.  Start iTunes with the option (shift on Windows) key held down and guide it to the new location of the library.
    iTunes: How to share music between different accounts on a single computer - http://support.apple.com/kb/HT1203 - relocating iTunes' media folder to a shared area but leaving separate library files - extra tip at https://discussions.apple.com/message/17331189
    Chris CA's instructions on sharing one iTunes music library between multiple user accounts - https://discussions.apple.com/message/8974074 - Multiple users using a single library file - similar post at: https://discussions.apple.com/thread/3753008
    Note that a device will not like being synced with multiple computers.

  • How to using ical with two separate iphones

    hello
    trying to understand and learn how to use Ical with 2 different Iphones, using Icloud.

    To sync iCal across computers, the calendar needs to be published to a server. This can be a local server that you can set up, or it can be something like google or microsoft exchange or apple's mobile me. The best bet may be to wait until fall and see what iCloud offers!
    Sharing your screen can be accomplished a few different ways. You can have two iChat accounts set up, and have one logged in on each computer, and then use iChat's screen share feature. The other way is to go to System Preferences, Sharing, and then check the box next to Screen Sharing. You may have to adjust some of the settings in there, but give that a shot.

Maybe you are looking for

  • Solution for error 2356

    Hi, has anyone found a solution for iTunes installation error:2356? I noticed a post since Dec last year, and no answers were found. Still having trouble installing itunes... sigh

  • IPhoto '08 resizing images (but not all)

    I have recently run into a problem which I assume is iphoto related. I never use iphoto because quite frankly I don't like it and I never have, which is why I stuck with '08 and didn't bother upgrading and this issue hasn't helped any. I decided to d

  • Power consumption when PowerOFF: 24" iMac 2009

    I really wonder about my iMac 2009 Modell: when using sleep mode I got 11-12 watts power consumption. But when shutting down the iMac (Power Off in Apple Menu), the same iMac takes 10 watts Is this normal and how can I get sleep mode with far less or

  • Func. Module - RH_EDITOR_SET giving Short Dump

    Hello , I am using a container in my proogram.While running this my program calls this function module and then it is giving a shortdump.The short text of that dump says "Exception condition "INTERNAL_ERROR" raised." the dump is coming at the line:  

  • 1.83ghz Macbook and Adobe/Macromedia ??

    I'm a poor student at the moment and I'm considering the Macbook 1.83 because I already have access to a dvd burner if needed so don't want to pay the extra $400 for the 2.0Ghz model. That being said does anyone know if this MacBook will be adequate