简体   繁体   English

如何将我所做的另一个查询结果添加到结果中(SQL)

[英]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请回答我

You don't need count(if()) to do what you want.你不需要count(if())来做你想做的事。 It is much simpler to use sum() as in:使用sum()简单得多,如下所示:

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.仅对字符串和日期/时间常量使用单引号。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM