我想在下面的select查询返回的COUNT_A上运行CASE语句或IF,并设置变量A_VAL的值。
SELECT A_DATE, COUNT(A_INS_NAM) AS COUNT_A
FROM TABLE1
WHERE A_INS_NAM IN
(
SELECT A_INS_NAM FROM IWD
WHERE I_ID IN
(
SELECT IM_ID FROM TIM WHERE IM_ID = (
SELECT T_ID FROM TWS WHERE TN = 'abced')
)
) AND A_DATE BETWEEN '2014-01-01' AND '2015-05-01' AND A_INS_NAM NOT LIKE '%pk%'
我希望输出有2列,即A_DATE,A_VAL。 A_VAL的值基于
设置If COUNT_A = 10, then A_VAL = 1
If COUNT_A = 20, then A_VAL = 2
If COUNT_A between 30 & 50, then A_VAL = 3
If COUNT_A > 50, then A_VAL = 5
我能得到别人的帮助吗?
答案 0 :(得分:1)
您应该使用联接而不是子查询以获得更好的性能,如下所示,您也使用聚合函数而不提供分组条件,因此它将作为单行产生,我在下面的查询中添加了GROUP BY t.A_DATE
SELECT
t.A_DATE,
CASE
WHEN COUNT(t.A_INS_NAM) = 10 THEN 1
WHEN COUNT(t.A_INS_NAM) = 20 THEN 2
WHEN COUNT(t.A_INS_NAM) BETWEEN 30 AND 50 THEN 3
WHEN COUNT(t.A_INS_NAM) > 50 THEN 5
ELSE 'some value'
END AS A_VAL
FROM
TABLE1 t
JOIN IWD t1 ON(t.A_INS_NAM = t1.A_INS_NAM)
JOIN TIM t2 ON(t1.IWD = t2.IM_ID)
JOIN TWS t3 ON(t2.IM_ID = t3.T_ID )
WHERE t3.TN = 'abced'
AND t.A_DATE BETWEEN '2014-01-01' AND '2015-05-01'
AND t.A_INS_NAM NOT LIKE '%pk%'
GROUP BY t.A_DATE