0

Here's the table I start with

CMS   |   defect_status 
________________________
1     |   true
2     |   false
3     |   true
3     |   false

and here's what I want

   CMS    |      true_defects    |   false_defects
   1      |      1               |   0
   2      |      0               |   1
   3      |      1               |   1

So here's my code

SELECT DISTINCT
    false_table.CMS, 
    true_table.true_defects,
    false_table.false_defects

FROM(
    SELECT DISTINCT 
        CMS,
        COUNT(*) AS true_defects 
    FROM data_table
    WHERE defect_status = 'true'
    GROUP BY CMS 
) as true_table

FULL JOIN(
    SELECT DISTINCT 
        CMS,
        COUNT(*) AS false_defects 
    FROM data_table
    WHERE defect_status = 'false'
    GROUP BY CMS 
) as false_table
ON true_table.CMS = false_table.CMS

I would like to select all CMS, those in "false_table" and "true_table". If I select "false_table.CMS" (as in the code above), here's what I get :

CMS    |      true_defects    |   false_defects
2      |      0               |   1
3      |      1               |   1

CMS "1" has disappeared simply because it's not in the column false_table.CMS

Thank you

Jdoe
  • 89
  • 1
  • 7

1 Answers1

1

You can achieve it by simple case and group by as below:

SELECT t1.CMS
    ,sum(CASE defect_status
            WHEN true
                THEN 1
            ELSE 0
            END) AS true_status
    ,sum(CASE defect_status
            WHEN false
                THEN 1
            ELSE 0
            END) AS false_status
FROM Table1 AS t1
GROUP BY CMS

Demo link: http://sqlfiddle.com/#!17/8478d/1

Mittal Patel
  • 2,732
  • 14
  • 23