Need a Query on group by condition

  • Hi ALL,

    I have one table which contines 3 columns they are

    1.emp

    2.monthyear

    3.amount

    in that table i am having 6 rows like below.

    emp monthyear amount

    1 102013 1000

    2 102013 1000

    1 112013 1000

    1 112013 1000

    2 122013 1000

    2 122013 0000

    i want a total on group by condition on each employee. which will have the data from NOV to dec 2013 only.

    out put should be like this

    1 2000

    2 1000

  • smharabbani40 (10/11/2013)


    Hi ALL,

    I have one table which contines 3 columns they are

    1.emp

    2.monthyear

    3.amount

    in that table i am having four rows like below.

    emp monthyear amount

    1 112013 1000

    1 112013 1000

    2 122013 1000

    2 122013 0000

    i want a total on group by condition on each employee.

    out put should be like this

    1 2000

    2 1000

    This looks a lot like homework. You will need to use SUM.

    http://technet.microsoft.com/en-us/library/ms187810.aspx

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Hi I need a Query from the month 112013 to 122013 sir......

    i have used the below Query which is not satisfieing.

    SELECT Emp,

    SUM (AMOUNT),

    Monthyear

    FROM table WHERE MonthYear between 112013 and 122013

    GROUP BY Emp

    Sorry to say ,if it very easy thing i wont put in here.

    anyhow thanks for your replay

  • smharabbani40 (10/11/2013)


    Hi I need a Query from the month 112013 to 122013 sir......

    i have used the below Query which is not satisfieing.

    SELECT Emp,

    SUM (AMOUNT),

    Monthyear

    FROM table WHERE MonthYear between 112013 and 122013

    GROUP BY Emp

    Sorry to say ,if it very easy thing i wont put in here.

    anyhow thanks for your replay

    That query won't run because you did not also group by Monthyear.

    It seems like Monthyear is an int datatype? If at all possible I would highly recommend changing to a date or datetime datatype instead. It will provide instant validation that the data entered is valid and it will let you do datemath without being forced to cast/convert it first.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Hi

    MonthYear is the INT data type.that is only the issue ,becuse of that between is not working....i can able to change datatype....

    if any suggestion/fixe rather than this please let me know.

    Thanks in advanced.............:-)

  • smharabbani40 (10/11/2013)


    Hi

    MonthYear is the INT data type.that is only the issue ,becuse of that between is not working....i can able to change datatype....

    if any suggestion/fixe rather than this please let me know.

    Thanks in advanced.............:-)

    Yeah the between is likely going to return values you don't want. Consider 122012. That would be december 2012 according to your pattern. It in fact does belong between 112013 and 122013 but it is not what you want in your query. This type of datemath is exactly what I was referring to in my first post. I would probably change this to a date datatype and then you can this type of query quite easily.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • declare @tbl table

    (

    emp int ,

    monthyear int,

    amount money

    )

    insert into @tbl

    select 1, 102013 ,1000

    union all select 2, 102013, 1000

    union all select 1, 112013 ,1000

    union all select 1, 112013, 1000

    union all select 2, 122013 ,1000

    union all select 2 ,122013,0000

    select emp, SUM(amount) from @tbl

    where LEFT(monthyear,2) = '11' or LEFT(monthyear,2) = '12'

    group by emp

    -------Bhuvnesh----------
    I work only to learn Sql Server...though my company pays me for getting their stuff done;-)

  • Bhuvnesh (10/13/2013)


    declare @tbl table

    (

    emp int ,

    monthyear int,

    amount money

    )

    insert into @tbl

    select 1, 102013 ,1000

    union all select 2, 102013, 1000

    union all select 1, 112013 ,1000

    union all select 1, 112013, 1000

    union all select 2, 122013 ,1000

    union all select 2 ,122013,0000

    select emp, SUM(amount) from @tbl

    where LEFT(monthyear,2) = '11' or LEFT(monthyear,2) = '12'

    group by emp

    I'm thinking that there's a major problem with that solution. What is the absolute guarantee that data from another year won't be included in the table? The code also contains a non-SARGable WHERE clause that will guarantee a table scan rather than a seek and range scan.

    The absolute best thing to do here would be to store the date data correctly. Using INT to store date data isn't the best way. It could certainly be improved by storing the date in the INT in a sortable fashion (yyyymm instead of mmyyyy) but that's still not the best way.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Sean Lange (10/11/2013)


    smharabbani40 (10/11/2013)


    Hi I need a Query from the month 112013 to 122013 sir......

    i have used the below Query which is not satisfieing.

    SELECT Emp,

    SUM (AMOUNT),

    Monthyear

    FROM table WHERE MonthYear between 112013 and 122013

    GROUP BY Emp

    Sorry to say ,if it very easy thing i wont put in here.

    anyhow thanks for your replay

    That query won't run because you did not also group by Monthyear.

    It seems like Monthyear is an int datatype? If at all possible I would highly recommend changing to a date or datetime datatype instead. It will provide instant validation that the data entered is valid and it will let you do datemath without being forced to cast/convert it first.

    Plus 1 billion to that.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Hi Thanks all for your support on the Query posted by me.

    i think i should give the exact data here.

    the data in the table is mentioned below.

    EMP MONTHY AMOUNT

    1 12013 1000

    1 22013 1000

    1 32013 1000

    2 12013 1000

    2 32013 0000

    2 42013 1000

    1 102013 1000

    1 112013 1000

    1 12014 1000

    1 22014 1000

    2 12014 0000

    2 22014 1000

    1 102014 1000

    2 102014 1000

    The Query should be give the data between 112013 to 102014. and the monthY column is the integer data type.

    i need a data as mentioned in the below format.

    EMP AMOUNT

    1 4000(THIS AMOUNT INCLUDES THE MONTHS FROM 112013 TO 102014)

    2 3000(THIS AMOUNT INCLUDES THE MONTHS FROM 112013 TO 102014)

    Please let me know if anybody have any fixes on the same.

    Thanks in advanced:-)

  • Here's a cte based solution.

    But, as already mentioned, this query is everything but efficient and clean code.

    From my point of view there are three options:

    a) get the MONTHY column into a datetime format, as already recommended or

    b) at least add a computed persisted column that'll do the same while keeping the "nasty column"

    c) live with what you have and be prepared for date conversion errors (e.g. MONTHY =152013) or at the very least invalid date values.

    I'd go with option (a).

    declare @tbl table

    (

    emp int ,

    monthyear int,

    amount money

    )

    INSERT INTO @tbl

    SELECT 1, 102013 ,1000

    UNION ALL SELECT 2, 102013, 1000

    UNION ALL SELECT 1, 112013 ,1000

    UNION ALL SELECT 1, 112013, 1000

    UNION ALL SELECT 2, 122013 ,1000

    UNION ALL SELECT 2 ,122013,1000

    UNION ALL SELECT 1, 12014 ,1000;

    WITH cte AS

    (

    SELECT

    CAST(RIGHT(monthyear,4) + LEFT(1000000 + monthyear,2) + '01' AS DATE) AS YYYYMMDD,

    emp,

    amount

    FROM @tbl

    )

    SELECT emp, SUM(amount) AS TotalAmount

    FROM cte

    WHERE YYYYMMDD >='20131101' AND YYYYMMDD <'20141001'

    GROUP BY emp



    Lutz
    A pessimist is an optimist with experience.

    How to get fast answers to your question[/url]
    How to post performance related questions[/url]
    Links for Tally Table [/url] , Cross Tabs [/url] and Dynamic Cross Tabs [/url], Delimited Split Function[/url]

  • Try this: (not tested)

    select emp

    , SUM(amount)

    , '(THIS AMOUNT INCLUDES THE MONTHS FROM ' + cast(min(monthyear) as char(6)) + ' TO ' + cast(max(monthyear) as char(6)) + ')'

    from @tbl

    where monthyear in(112013, 122013, 12014, etc, etc..... )

    group by emp

  • --create a new local table and add start date column and separating the month and year in the monthyyear column

    Declare @loc_table table (emp int, dates int, year int, amount money,startdate smalldatetime)

    Insert into @loc_table

    Select emp

    ,(case when len(monthyyear) = 6 then substring(monthyyear,1,2)

    when len(monthyyear) = 5 then substring(monthyyear,1,1)

    else ''

    end) as dates

    ,(case when len(monthyyear) = 6 then substring(monthyyear,3,4)

    when len(monthyyear) = 5 then substring(monthyyear,2,4)

    else ''

    end)as year

    ,amount

    ,null

    from tablename

    Update @loc_table

    SET startdate = dateadd(month,dates-1,dateadd(yy,year-1900,0))

    From @loc_table

    --input variables

    --need a Query from the month 112013 to 122014

    Declare @startdate smalldatetime

    ,@enddate smalldatetime

    ,@month1 int

    ,@year1 int

    ,@month2 int

    ,@year2 int

    ,@montyear1 varchar(10)

    ,@monthyear2 varchar(10)

    SET @montyear1 = 112013

    SET @monthyear2 = 122014

    --get the start date

    SET @month1 = (case when len(@montyear1) = 6 then substring(@montyear1,1,2)

    when len(@montyear1) = 5 then substring(@montyear1,1,1)

    else ''

    end)

    SET @year1 = (case when len(@montyear1) = 6 then substring(@montyear1,3,4)

    when len(@montyear1) = 5 then substring(@montyear1,2,4)

    else ''

    end)

    SET @startdate = dateadd(month,@month1-1,dateadd(yy,@year1-1900,0))

    --get the end date

    SET @month2 = (case when len(@monthyear2) = 6 then substring(@monthyear2,1,2)

    when len(@monthyear2) = 5 then substring(@monthyear2,1,1)

    else ''

    end)

    SET @year2 = (case when len(@monthyear2) = 6 then substring(@monthyear2,3,4)

    when len(@monthyear2) = 5 then substring(@monthyear2,2,4)

    else ''

    end)

    SET @enddate = dateadd(day,-1,dateadd(month,@month2,dateadd(yy,@year2-1900,0)))

    select emp, sum(amount) as Amount from @loc_table

    where Startdate between @startdate and @enddate

    group by emp

  • Hi try with this

    WITH cte AS

    (

    SELECT

    CAST(RIGHT(monthyear,4) + CASE WHEN LEN(monthyear)=6 THEN LEFT(monthyear,2) WHEN LEN(monthyear)=5

    THEN '0'+LEFT(monthyear,1) END + '01' AS DATE) AS YYYYMMDD,

    emp,

    amount

    FROM @tbl

    )

    SELECT emp, SUM(amount) AS TotalAmount ,'THIS AMOUNT INCLUDES THE MONTHS FROM ' + CONVERT(VARCHAR(10), MIN(YYYYMMDD)) + ' TO ' +CONVERT(VARCHAR(10), MAX(YYYYMMDD))

    FROM cte

    WHERE YYYYMMDD >='20130101' AND YYYYMMDD <'20140201'

    GROUP BY emp

Viewing 14 posts - 1 through 13 (of 13 total)

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