Regard Generate output for report

  • Here is my Dilemma

    i have a table abc with columns testId,gender

    with values

    testid gender

    1 1

    2 1

    3 2

    1 represent Male ,2 Represent Female

    i want the output like this

    testid male female

    1 1 0

    2 1 0

    3 0 1

    Thanks in advance

  • Hi

    You can use the CASE function for this. I dont have SQL installed in m/c now to give u the exact query.

    "Keep Trying"

  • DECLARE @Data TABLE (test_id INT PRIMARY KEY, gender TINYINT NOT NULL CHECK (gender BETWEEN 1 AND 2));

    INSERT @Data VALUES (1,1), (2,1), (3,2);

    SELECT

    test_id,

    male = CONVERT(BIT, gender - 2),

    female = CONVERT(BIT, gender - 1)

    FROM

    @Data;

  • Thanks

    for Your Immediate Response

    But TestId is not unique ,number of male can give same test ,then

    DECLARE @Data TABLE (test_id INT , gender TINYINT NOT NULL CHECK (gender BETWEEN 1 AND 2));

    INSERT @Data VALUES (1,1), (2,1), (3,2),(1,1) ;

    SELECT

    test_id,

    male = CONVERT(BIT, gender - 2),

    female = CONVERT(BIT, gender - 1)

    FROM

    @Data;

    in this case i want output like

    testid male female

    1 2 0

  • Hi,

    Both gives you correct direction for what you post first, but now you needs, the id repeated and counts the genders.

    DECLARE @Data TABLE

    (test_id INT ,

    gender INT )

    INSERT @Data VALUES (1,1)

    INSERT @Data VALUES (2,1)

    INSERT @Data VALUES (3,2)

    INSERT @Data VALUES (1,1)

    INSERT @Data VALUES (1,1)

    select test_id,(case when gender = 1 then count(gender)else 0 end)[Male],

    (case when gender = 2 then count(gender)else 0 end)[Female]

    from @Data

    group by test_id,gender

  • Please try to be more clear in your first post next time. Thank you.

Viewing 6 posts - 1 through 5 (of 5 total)

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