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

How do I add another column to query that needs to be filtered if I am already filtered for another column in the where clause?

I need help creating a report and I’m not sure if I should something I’ve been researching called a pivot? I have a table "UwrOTRNBaseRates", with 3 columns: State, RateType, and Rate. The report needs to be a column with State, then a column of rates filtered on ‘FMLY’ RateType, then a column of rates filtered on ‘SNGL’ RateType. I only know how to generate the report with either or of the rate type filters. I need help adding both. How do I add a third column for single rate if I’m already filtering on FMLY in the where clause? I built the report below in excel of what I am trying to accomplish in SQL.

SELECT State, Rate as FamilyRate 
FROM UwrOTRNBaseRates
WHERE RateType = 'FMLY'

Table Columns

What report should look like

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

>Solution :

This can be done using the conditional aggregation using the aggregation function sum() as follows :

SELECT State, sum(CASE WHEN RateType = 'FMLY' THEN 1 ELSE 0 END) AS FAMILY_RATE,
              sum(CASE WHEN RateType = 'SNGL' THEN 1 ELSE 0 END) AS SINGLE_RATE
FROM UwrOTRNBaseRates
GROUP BY State

Or using count() :

SELECT State, count(CASE WHEN RateType = 'FMLY' THEN 1 END) AS FAMILY_RATE,
              count(CASE WHEN RateType = 'SNGL' THEN 1 END) AS SINGLE_RATE
FROM UwrOTRNBaseRates
GROUP BY State
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