Need help in building Query

  • Hi Friends,

    Need help  building query. I have below data.

    Item Name  Delivered country

    TV 32 inch  USA

    TV 32 inch  UK

    Tv 32 inch India

    Tv 40 Inc India

    Tv 50  India

    Tv 50  UK

    If the Item is delivered in more than one country i should be consider as Global. I am looking for the below output.

    Item Name  Delivered country

    TV 32 inch  Global

    Tv 40 Inc India

    Tv 50  Global

     

    Regards

    Prakash

     

  • What have you tried?

    A few things to think about. When you note that something is in more than one  country, you're considering that it has appeared in more than one row. You might look at a COUNT(*) aggregate for the items. Then you can replace the value of the country with the  word "Global'

    Hint, use a CTE:

    with mycte
    as
    (select * from mytable)
    select *
    from mytable
    inne join mycte
    on mytable.pk = mycte.pk
  • Steve Jones - SSC Editor wrote:

    What have you tried?

    A few things to think about. When you note that something is in more than one  country, you're considering that it has appeared in more than one row. You might look at a COUNT(*) aggregate for the items. Then you can replace the value of the country with the  word "Global'

    Hint, use a CTE:

    with mycte
    as
    (select * from mytable)
    select *
    from mytable
    inne join mycte
    on mytable.pk = mycte.pk

    I don't think that you really need to use a CTE, but you certainly don't want to use a join.  You only need one scan of the table and joining would add an unnecessary scan.

    Also, unless item/delivered country is a unique key I would use a distinct count instead of a non-distinct count. (An alternate version would be to compare the MIN() and MAX() values.)

    Drew

    • This reply was modified 5 years ago by  drew.allen.

    J. Drew Allen
    Business Intelligence Analyst
    Philadelphia, PA

  • I guessed you would want to sort/order by Item first; if not, you might want to reverse the GROUP BY to Name, Item.

    SELECT Item, Name, 
    CASE WHEN COUNT(*) = 1 THEN MAX([Delivered country]) ELSE 'Global' END AS [Delievered Country]
    FROM dbo.table_name
    GROUP BY Item, Name
    ORDER BY Item, Name

    SQL DBA,SQL Server MVP(07, 08, 09) "Money can't buy you happiness." Maybe so, but it can make your unhappiness a LOT more comfortable!

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply