0

我有一个包含元素的表。

每个元素都有它的 parent instance_id、 a number_of_linesof code 和 a deletion_datewhen removed。

我构建了一个查询,该查询对按实例分组的元素进行计数,其中包含具有代码(number_of_lines非零)和已删除元素(deletion_date非空)的元素的总数

SELECT instance_id, 
    COUNT(id) AS elementsfound,
    COUNT(NULLIF(number_of_lines,0)) AS havecode,
    (COUNT(id)-COUNT(NULLIF(number_of_lines,0))) AS havenocode,      
    COUNT(deletion_date) AS beenremoved,          
    (COUNT(id)-COUNT(deletion_date)) AS stillexistent        
  FROM elements        
  GROUP BY instance_id

我得到(缩写)的正确结果

+-------------+---------------+----------+------------+-------------+---------------+
| instance_id | elementsfound | havecode | havenocode | beenremoved | stillexistent |
+-------------+---------------+----------+------------+-------------+---------------+
|          59 |         93123 |    24109 |      69014 |       45397 |         47726 |
|          69 |         46399 |     7837 |      38562 |       23929 |         22470 |
|          71 |         41752 |     8746 |      33006 |        6960 |         34792 |
|          75 |         29097 |     4303 |      24794 |       13670 |         15427 |
|          77 |         41681 |     9858 |      31823 |       10540 |         31141 |
|          79 |         17800 |      695 |      17105 |       13391 |          4409 |
|          82 |         25323 |     2481 |      22842 |       20914 |          4409 |
|          83 |         12831 |     2544 |      10287 |        2988 |          9843 |

...

现在,我想添加一个列,其中包含每个实例仍然存在(deletion_date为空)并且具有代码(number_of_lines不同于零)的元素数

我发现没有办法添加 aNULLIF或 aCASE WHEN与多列。

如何包含多列条件计数器?

4

2 回答 2

1

你想做吗?

sum( if(deletion_date is null and number_of_lines!=0, 1, 0) )
于 2020-01-15T17:06:05.453 回答
1

我假设你的意思是仍然存在的记录应该有 delete_date NULL。

试试这个:

SELECT instance_id, 
    COUNT(id) AS elementsfound,
    COUNT(NULLIF(number_of_lines,0)) AS havecode,
    (COUNT(id)-COUNT(NULLIF(number_of_lines,0))) AS havenocode,      
    COUNT(deletion_date) AS beenremoved,          
    (COUNT(id)-COUNT(deletion_date)) AS stillexistent,
    COUNT(IF(deletion_date IS NULL AND number_of_lines > 0, 1, NULL)) existentwithcode
  FROM elements        
  GROUP BY instance_id
于 2020-01-15T17:13:28.150 回答