Generating Frequency and Percentage in SQL Server

Posted on 2007-08-06
Last Modified: 2008-02-01
I have the data in my SQL Server tables like below
CaseID  Variable  Value
1            Married   1
2            Married   0
3            Married   1
4            Married   0
5            Married   1

I want the freqs and percentage like

VariableName  Code  Freqs Percent
Married              1          3     60
Married              0          2     40

Is there something in SQL Server to efficiently create frequency and percentage for the data similar to SAS or other Statistical Software? My current option is to write SAS program to read the data and generate the freqs and percentage, Wanted to find out what if any options are available in SQL Server.

Question by:asp123
    LVL 8

    Assisted Solution

    select  variable, [value], count(*) as frequency,
    ((select  cast (count(*) as float) from status s2 where s2.value=s1.value
    group by  variable, value)/(select cast (count(*) as float) from status
    s3 where s1.variable=s3.variable group by variable)*100) as percentage from status s1
    group by  variable, value
    LVL 68

    Accepted Solution

    For efficiency, it's best to use a temp table, otherwise you have to scan the main table too many times.  For example [code below uses NULL to get grand total; if you have nulls in the actual values, you will need to use some other value]:

    /* -- use to create sample data
    set nocount on
    drop table #tablename
    create table #tablename (
        caseid int,
        variable varchar(40),
        value int
    insert into #tablename values(1 ,         'Married'  ,1)
    insert into #tablename values(2  ,        'Married'  ,0)
    insert into #tablename values(3   ,       'Married'  ,1)
    insert into #tablename values(4    ,      'Married' , 0)
    insert into #tablename values(5     ,     'Married',  1)

    IF OBJECT_ID('tempdb.dbo.#work') IS NOT NULL
        DROP TABLE #work
    CREATE TABLE #work (
        variable VARCHAR(40),
        value INT,
        valueCount INT,
        UNIQUE CLUSTERED (variable, value)

    INSERT INTO #work
    SELECT variable,
        CASE WHEN whichTotal = 'value' THEN value ELSE NULL END AS [value],
        COUNT(*) AS [valueCount]
    FROM #tableName
        SELECT 'value' AS whichTotal UNION ALL  --total for an individual value
        SELECT 'variable'  --grand total for a variable (all values for one variable)
    ) AS whichTotals
    GROUP BY variable,
        CASE WHEN whichTotal = 'value' THEN value ELSE NULL END
    ORDER BY variable, value


    SELECT variable AS VariableName,
        value AS Code,
        valueCount AS Freqs,
        CAST(valueCount * 100.0 / (SELECT valueCount FROM #work w2
            WHERE w2.variable = w1.variable AND w2.value IS NULL) AS INT)
        AS [Percent]
    FROM #work w1
    ORDER BY variable, value
    LVL 50

    Assisted Solution

    Select x.*
          ,convert(decimal(3,0),((x.Freq/Y.TotFreq) * 100)) as Percent
      From (
    select variable,value,convert(decimal(9,3),count(*)) as Freq
      from yourtable
     group by variable,value
    ) as x
    Inner Join
     ( select variable,Count(distinct value) as NoVal,Count(*) as TotFreq
        from yourtable
       group by variable
     ) as Y
     on x.variable=y.variable
    order by a.variable,a.value

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
    JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
    This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
    Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now