根据以前的案例陈述,有人知道计数的解决方案吗?
这就是我在查询中的含义,无法正常工作
SELECT
CASE
WHEN field1 IN ('a','b','c') THEN 'MATCH1'
WHEN field2 IN ('d','e','f') THEN 'MATCH2'
ELSE 'NOMATCH' END AS MATCHFIELD,
(SELECT COUNT(*) FROM TABLE2 WHERE field3=MATCHFIELD) AS SUBCOUNT
FROM TABLE1
我在db2 v9.X上。 我尝试过 HAVING 但找不到可行的解决方案
问候
答案 0 :(得分:3)
将SELECT
表达式case
包含在派生表中:
select MATCHFIELD,
(SELECT COUNT(*) FROM TABLE2 WHERE field3=MATCHFIELD) AS SUBCOUNTSELECT
from
(
select
CASE
WHEN field1 IN ('a','b','c') THEN 'MATCH1'
WHEN field2 IN ('d','e','f') THEN 'MATCH2'
ELSE 'NOMATCH'
END AS MATCHFIELD
FROM TABLE1
) dt
答案 1 :(得分:1)
我会使用JOIN
和GROUP BY
SELECT MATCHFIELD, COUNT(*)
FROM TABLE2
JOIN
(
SELECT
CASE
WHEN field1 IN ('a','b','c') THEN 'MATCH1'
WHEN field2 IN ('d','e','f') THEN 'MATCH2'
ELSE 'NOMATCH' END AS MATCHFIELD
FROM TABLE1
) t ON field3=t.MATCHFIELD
GROUP BY MATCHFIELD
答案 2 :(得分:1)
试试这个:
with tmp as (
SELECT CASE
WHEN field1 IN ('a','b','c') THEN 'MATCH1'
WHEN field2 IN ('d','e','f') THEN 'MATCH2'
ELSE 'NOMATCH' END AS MATCHFIELD
FROM TABLE1
)
select tmp.*, (SELECT COUNT(*) FROM TABLE2 WHERE field3=MATCHFIELD) AS SUBCOUNT
from tmp