Count of records with different conditions in the same select statement

  • How do I put these two select statement into one result set?

    (Select Count(*) As SRIP FROM dbo.tblContracts C WHERE C.ACTION_CODE='SOLD_000003'

    AND C.IT_Code = 'SRIP'

    AND C.ContractStatus = 'A' AND C.UnitState = 'AZ'),

    (Select Count(*) As TA FROM dbo.tblContracts C

    WHERE C.ACTION_CODE='SOLD_000003'

    AND CI.IT_Code = 'TA'

    AND C.ContractStatus = 'A' AND C.UnitState = 'AZ')

  • Does this work?

    select

    (Select Count(*) As SRIP FROM dbo.tblContracts C WHERE C.ACTION_CODE='SOLD_000003'

    AND C.IT_Code = 'SRIP'

    AND C.ContractStatus = 'A' AND C.UnitState = 'AZ') as SRIP,

    (Select Count(*) As TA FROM dbo.tblContracts C

    WHERE C.ACTION_CODE='SOLD_000003'

    AND CI.IT_Code = 'TA'

    AND C.ContractStatus = 'A' AND C.UnitState = 'AZ') as Ta

  • I will try it.

    Thanks

  • it did not work.

  • What result set are you wanting to get?

    That should have returned 1 row with 2 columns

  • Another variation:

    Select sum(case C.IT_Code when 'SRIP' then 1 else 0 end) as SRIP,

    sum(case C.IT_Code when 'TA' then 1 else 0 end) as TA

    FROM dbo.tblContracts C

    WHERE C.ACTION_CODE='SOLD_000003'

    AND C.ContractStatus = 'A' AND C.UnitState = 'AZ'

    AND C.IT_Code in ('SRIP', 'TA')

    /Kenneth

  • I will try the Sum Statement.

    Thanks

  • It worked.

    thank you very much.

  • I was trying to come up with something exactly like this before, but couldn't ever quite get it, so thanks!

    What I had been doing (translated to this example) was essentially this:

    SELECT

    (SELECT COUNT(*) FROM dbo.tblContracts WHERE IT_Code = 'SRIP' AND ACTION_CODE = C.ACTION_CODE AND ContractStatus = C.ContractStatus AND UnitState = C.UnitState) AS SRIP,

    (SELECT COUNT(*) FROM dbo.tblContracts WHERE IT_Code = 'TA' AND ACTION_CODE = C.ACTION_CODE AND ContractStatus = C.ContractStatus AND UnitState = C.UnitState) AS TA

    FROM dbo.tblContracts

    WHERE C.ACTION_CODE = 'SOLD_000003'

    AND C.ContractStatus = 'A'

    AND C.UnitState = 'AZ'

    Obviously, in this example, it's a lot of overkill. But in mine, I was doing a GROUP BY and getting other aggregate data for the whole group as well as the counts for the things like IT_Code in this example.

    But, I just tried the SUM and CASE in mine, and it works great as well! Also, it runs in about half the time.

  • Thanks again. your solution was great.

Viewing 10 posts - 1 through 9 (of 9 total)

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