Create New Table - Count Columns

  • Hi all,

     

    I am new to writing SQL code and am wondering the best way to create a new table from an existing table that has count columns as shown below

     

    Existing Table:

    [candidateref]

    [candidate postcode]

     

     

    Required Table

     

     

    Thank you,

     

    HPBI

  • Depends on what ur looking for, are you looking for a count or a distinct count (counting each ref only once, ignoring duplicates)

    Maybe something like this case when helps

    select [candidateref]
    ,[candidate postcode]
    --Count
    ,sum(case when POSTCODE IS NULL
    THEN 1
    else 0 END)
    ,sum(case when POSTCODE IS NOT NULL
    THEN 1
    else 0 END)
    --Distinct count, -1 because of the default 'XXXX'
    ,count(distinct
    case when POSTCODE IS NULL
    THEN [candidateref]
    else 'XXXX' END)-1
    ,count(distinct
    case when POSTCODE IS NOT NULL
    THEN [candidateref]
    else 'XXXX' END)-1
  • I tried below:

     

    select [candidateref],

    [candidatepostcode],

    Count([candidatepostcode]),sum(case when [candidatepostcode] IS NULL THEN 1 else 0 END) ,

    sum(case when [candidatepostcode] IS NOT NULL THEN 1 else 0 END)

    from [CandidateGeoLocation]

     

    but received the below error

     

    Msg 8120, Level 16, State 1, Line 1

    Column 'CandidateGeoLocation.CandidateRef' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

  • Every column thats used in select but not  an aggregation (avg/sum/...) needs to be in the group by after the from:

    group by [candidateref],                 
    [candidatepostcode]?
  • Thank you! How do I then create a table for this statement?

  • Hi...just wondering why you would want to create a table with just one row from these results?

    Also....what do you want to record when the postcode column is just an empty string and not "NULL"  ?

    ________________________________________________________________
    you can lead a user to data....but you cannot make them think
    and remember....every day is a school day

  • This was removed by the editor as SPAM

  • This was removed by the editor as SPAM

Viewing 8 posts - 1 through 7 (of 7 total)

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