我正在尝试根据特定列的值以不同的方式提取字段值的计数(作为两个不同的值(,即 jjsc_rev_cycle
就我而言。
如果jjsc_rev_cycle
0
然后得到
count(distinct jjsc_job_no) as new_order_count
还
count(distinct jjsc_job_no) as rev_order_count
我试图在 1 个这样的查询中执行此操作,但说语法错误:
SELECT jjsc_rev_cycle,
CASE jjsc_rev_cycle
WHEN jjsc_rev_cycle = 0
THEN select count(distinct jjsc_job_no) as new_order_count
ELSE select count(distinct jjsc_job_no) as rev_order_count
END
FROM jdwf_job_status_cycle
WHERE jjsc_time >= '2017-06-01' and jjsc_time <= '2017-06-03' group
by jjsc_wf_userid
示例表数据:
jjsc_job_no jjsc_rev_cycle jjsc_time
7201170 0 2019-06-12 15:49:26
7201171 0 2019-06-12 15:35:56
7201172 0 2019-06-12 15:31:49
7201162 0 2019-06-12 15:31:15
7201166 1 2019-06-12 15:30:39
7201169 0 2019-06-12 15:29:22
7201164 0 2019-06-12 15:28:38
7201168 0 2019-06-12 15:27:55
7201167 0 2019-06-12 15:26:49
7201165 0 2019-06-12 15:25:51
7201161 0 2019-06-12 15:24:28
7201160 0 2019-06-12 15:22:21
7201159 0 2019-06-12 15:21:13
7201158 0 2019-06-12 15:20:16
7200991 0 2019-06-11 16:18:15
7200999 0 2019-06-11 14:38:48
7200991 1 2019-06-11 14:37:56
7200984 0 2019-06-11 14:37:06
7201097 0 2019-05-30 12:55:43
预期产出:
new_order_count rev_order_count
17 2
我做错了什么?还是有其他方法可以做到这一点?
您在问题中使用了count(distinct)
,因此我认为这是必要的。 如果是这样,正确的逻辑是:
SELECT jjsc_wf_userid,
COUNT(DISTINCT CASE WHEN jjsc_rev_cycle = 0 THEN jjsc_job_no END) as new_order_count,
COUNT(DISTINCT CASE WHEN jjsc_rev_cycle <> 0 THEN jjsc_job_no END) as rev_order_count
FROM jdwf_job_status_cycle
WHERE jjsc_time >= '2017-06-01' AND
jjsc_time < '2017-06-04'
GROUP BY jjsc_wf_userid
请注意,我更改了"时间"比较的第二个限制。 据推测,jjsc_time
有一个时间分量。 在任何情况下,无论有没有时间分量,此逻辑都是安全的。
如果您不需要COUNT(DISTINCT)
则可以将其简化为:
SELECT jjsc_wf_userid,
SUM(jjsc_rev_cycle = 0) as new_order_count,
SUM(jjsc_rev_cycle <> 0) as rev_order_count
FROM jdwf_job_status_cycle
WHERE jjsc_time >= '2017-06-01' AND
jjsc_time < '2017-06-04'
GROUP BY jjsc_wf_userid
您无法在机箱内执行聚合,但在我看来,您需要在下面
SELECT jjsc_rev_cycle, sum(case when jjsc_rev_cycle = 0 then 1 else 0 end)
as new_order_count,
sum(case when jjsc_rev_cycle!= 0 then 1 else 0 end) as rev_order_count
FROM jdwf_job_status_cycle
WHERE jjsc_time >= '2017-06-01' and jjsc_time <= '2017-06-03' group
by jjsc_wf_userid
在处理示例数据后我认为您需要在使用案例之前应用不同的情况
SELECT jjsc_wf_userid, sum(case when jjsc_rev_cycle = 0 then 1 else 0 end)
as new_order_count,
sum(case when jjsc_rev_cycle!= 0 then 1 else 0 end) as rev_order_count
from
(
select distinct jjsc_wf_userid,jjsc_job_no,jjsc_rev_cycle
FROM jdwf_job_status_cycle
) a group by jjsc_wf_userid