1

我有 2 个查询,2 个计数。但是当我写我的语句 count(), count() 时,我在两列中得到相同的计数。你能帮帮我吗?

我已经尝试了不同的方法(最后一个例子)

这是我的两个单独的查询

SELECT 
    x.ROWa, x.ROWb, COUNT(*) ResultA 
FROM
    tableA x
LEFT JOIN 
    tableB AS y ON SUBSTR(x.ROWb, 4, 1) = y.ROWz
WHERE 
    x.ROWc IN (5, 6) 
    AND (SUBSTR(x.ROWb, 4, 1) = "6" OR SUBSTR(x.ROWb, 4, 1) = "9") 
    AND Workflow = "VALUEone" 
    AND Shorthistory = "False"
GROUP BY 
    1
ORDER BY
    3 DESC, 2, 1 ASC

SELECT 
    x.ROWa, x.ROWb, COUNT(*) ResultB 
FROM
    tableA x
LEFT JOIN 
    tableB AS y ON SUBSTR(x.ROWb, 4, 1) = y.ROWz
WHERE 
    x.ROWc IN (5, 6) 
    AND (SUBSTR(x.ROWb, 4, 1) = "6" OR SUBSTR(x.ROWb, 4, 1) = "9") 
    AND Status = "successfull"
GROUP BY
    1
ORDER BY
    3 DESC, 2, 1 ASC

简而言之,我得到的是:

ROWa|ROWb|ResultA|ResultB
-------------------------
aaa |123 |78    |78
bbb |456 |30    |30

但它应该给出实际结果:

ROWa|ROWb|ResultA|ResultB
-------------------------
aaa |123 |78    |250
bbb |456 |30    |74

我尝试了什么:

SELECT 
    x.ROWa, x.ROWb, 
    COUNT((SELECT x.ROWb 
           FROM tableA x
           LEFT JOIN tableB AS y ON SUBSTR(x.ROWb, 4, 1) = y.ROWz
           WHERE x.ROWc IN (5, 6) 
             AND (SUBSTR(x.ROWb, 4, 1) = "6" OR SUBSTR(x.ROWb, 4, 1) = "9") 
             AND Workflow = "VALUEone" 
             AND Shorthistory = "False"
           GROUP BY 1)) ResultA,
    COUNT((SELECT x.ROWb 
           FROM tableA x
           LEFT JOIN tableB AS y ON SUBSTR(x.ROWb, 4, 1) = y.ROWz
           WHERE x.ROWc IN (5, 6) 
             AND (SUBSTR(x.ROWb, 4, 1) = "6" OR SUBSTR(x.ROWb, 4, 1) = "9") 
             AND Status = "successfull"
           GROUP BY 1)) ResultB
GROUP BY
    1
ORDER BY
    3 DESC, 2, 1 ASC
4

1 回答 1

0

如果您使用条件聚合,您可以将 2 个查询合并为 1 个:

SELECT x.ROWa, x.ROWb, 
       COUNT(CASE WHEN Workflow = 'VALUEone' AND Shorthistory = 'False' THEN 1 END) ResultA,
       COUNT(CASE WHEN Status = 'successfull' THEN 1 END) ResultB  
FROM tableA x LEFT JOIN tableB y 
ON SUBSTR(x.ROWb, 4, 1) = y.ROWz
WHERE x.ROWc in (5,6) AND SUBSTR(x.ROWb,4,1) IN ('6', '9') 
GROUP BY x.ROWa

或者:

SELECT x.ROWa, x.ROWb, 
       SUM(Workflow = 'VALUEone' AND Shorthistory = 'False') ResultA,
       SUM(Status = 'successfull') ResultB  
FROM tableA x LEFT JOIN tableB y 
ON SUBSTR(x.ROWb, 4, 1) = y.ROWz
WHERE x.ROWc in (5,6) AND SUBSTR(x.ROWb,4,1) IN ('6', '9')  
GROUP BY x.ROWa
于 2021-07-16T19:02:05.303 回答