Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combination of SQL Select Statments

I am trying to take a "snapshot" of a state of some tables of our database. I have finished a few of them and I am currently working on the last, however for the last one I need to query two different tables.

So far have tried the following:

SELECT
     COUNT(Name) as CRIT,
     branch
FROM(
SELECT
    A.Name,
    A.branch,
    B.score,
    B.last_found
FROM
    TableA as A
INNER JOIN TableB as B ON A.Name= V.Name
WHERE
    B.state <> 'DONE'
AND DATEDIFF(day, B.last_found, GETDATE()) > 30
AND CAST(B.score as float) > 8) AS X
GROUP BY
    branch

This will return me a portion of what I need:
(https://i.stack.imgur.com/fGIgo.png)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can slightly modify the code:

SELECT
     COUNT(Name) as LOW,
     branch
FROM(
SELECT
    A.Name,
    A.branch,
    B.score,
    B.last_found
FROM
    TableA as A
INNER JOIN TableB as B ON A.Name= V.Name
WHERE
    B.state <> 'DONE'
AND DATEDIFF(day, B.last_found, GETDATE()) > 30
AND CAST(B.score as float) < 4) AS X
GROUP BY
    branch

to get the following:
(https://i.stack.imgur.com/PILiX.png)

This is once again another portion of what I need. The final output should be a combination of the two above queries and should have 3 columns:

CRIT LOW Branch

Apologies if I am unclear and thank you for helping!!

>Solution :

You want conditional aggregation (CASE expression inside an aggregation function):

SELECT
   a.branch,
   COUNT(CASE WHEN CAST(b.score as float) > 8 THEN 1 END) AS crit,
   COUNT(CASE WHEN CAST(b.score as float) < 4 THEN 1 END) AS low
FROM tablea AS a
INNER JOIN tableb AS b ON b.name = a.name
WHERE b.state <> 'DONE'
AND DATEDIFF(day, b.last_found, GETDATE()) > 30
GROUP BY a.branch;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading