0

I am developping a simple criminal records management system using SQL Server.

I have the following tables:

Criminal (
          CriminalID,
          Gender ...)

Victim (
        VictimID,
        Gender ...)

Crime(
       CrimeID, 
       CriminalID,
       VictimID ...)

I am interested in creating a view that gives us a simple statistic about Gender of victims by gender of criminals.

Example of wanted output:

Victim \ Criminal | Male | Female

Male              |  4   | 2

Female            |   8  | 5

Grouping the Number of crimes only by gender of victims or only by gender of criminals isnt hard , But how can i perform this task ? How to Expand the Gender of criminals into 2 separate columns and perform the needed task ?

1
  • add some subquery columns Commented May 24, 2015 at 11:44

1 Answer 1

1

You need a conditional sum:

select criminal.gender
  ,SUM(case when victim.gender = 'M' then 1 else 0 end) as "Male"
  ,SUM(case when victim.gender = 'F' then 1 else 0 end) as "Female"
from ...
group by criminal.gender

The CASE returns either 1 or 0...

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much sir it worked I have a little question : can we expand the same query in the case the values of the second column are multiple ? i mean in this case it was possible since the values that gender can take is known ; is there a way we do the same operation in case for example for age (where we may have wide range of possible values that age can take) ?
@user3179490: You need to know the actual values for age and then it's SUM(case when age between 18 and 25 then 1 else 0 end). You might also look at the PIVOT functionality in SQL Server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.