Hoonjo
Hoonjo

Reputation: 21

How to add another result of query that result i made to a result (SQL)

Hi I have a problem with this This would be simple to you but I couldn't find out how to fix my code because of my bad English :((

Here is the query I made

SELECT  
  ESCC,
  count(if(DRC =156, DRC,NULL)) AS 'A',
  count(if(DRC =159, DRC,NULL)) AS 'B',
  count(if(DRC =160, DRC,NULL)) AS 'C'
FROM diag_results WHERE diagOrder=1 GROUP BY ESCC;

The query above produces the following result.

+------+----+----+----+
| ESCC | A  | B  | C  |
+------+----+----+----+
|    1 | 32 | 21 | 92 |
+------+----+----+----+
|    2 | 21 | 33 | 52 |
+------+----+----+----+
...

But I'd like to add another result of bellow query to that above result as columns

SELECT  
  count(if(DRC =156, DRC,NULL)) AS 'D',
  count(if(DRC =159, DRC,NULL)) AS 'E',
  count(if(DRC =160, DRC,NULL)) AS 'F'
FROM diag_results WHERE diagOrder=2 GROUP BY ESCC;

as a result of that

+----+----+----+
| D  | E  | F  |
+----+----+----+
| 32 | 21 | 92 |
+----+----+----+
| 21 | 33 | 52 |
+----+----+----+
...

So I want to get a result like this

+------+----+----+----+----+----+----+
| ESCC | A  | B  | C  | D  | E  | F  |
+------+----+----+----+----+----+----+
|    1 | 32 | 21 | 92 | 32 | 21 | 92 |
+------+----+----+----+----+----+----+
|    2 | 21 | 33 | 52 | 21 | 33 | 52 |
+------+----+----+----+----+----+----+

please answer me

Upvotes: 1

Views: 103

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269843

You don't need count(if()) to do what you want. It is much simpler to use sum() as in:

SELECT ESCC,
       sum(diagOrder = 1 and DRC = 156) AS A,
       sum(diagOrder = 1 and DRC = 159) AS B,
       sum(diagOrder = 1 and DRC = 160) AS C,
       sum(diagOrder = 2 and DRC = 156) AS D,
       sum(diagOrder = 2 and DRC = 159) AS E,
       sum(diagOrder = 2 and DRC = 160) AS F
FROM diag_results
WHERE diagOrder IN (1, 2) 
GROUP BY ESCC;

I also strongly dissuade you from using single quotes for column aliases. Use single quotes only for string and date/time constants.

Upvotes: 2

Dark Knight
Dark Knight

Reputation: 6541

SELECT  
  ESCC,
  count(if(diagOrder = 1 AND DRC =156, DRC,NULL)) AS 'A',
  count(if(diagOrder = 1 AND DRC =159, DRC,NULL)) AS 'B',
  count(if(diagOrder = 1 AND DRC =160, DRC,NULL)) AS 'C',
  count(if(diagOrder = 2 AND DRC =156, DRC,NULL)) AS 'D',
  count(if(diagOrder = 2 AND DRC =159, DRC,NULL)) AS 'E',
  count(if(diagOrder = 2 AND DRC =160, DRC,NULL)) AS 'F'
FROM diag_results WHERE diagOrder IN (1, 2) 
GROUP BY ESCC;

Upvotes: 0

Related Questions