[比较两列ftp_start_time和ftp_stop_time并根据条件返回列数:3列为1.Tried(count(ftp_start_time))2。成功(非空时计数ftp_start_time和ftp_stop_time)3。失败(计数) ftp_stop_time必须为null)..请帮忙
SELECT
a.Branch_code,
b.DevCount AS total,
COUNT(a.ftp_start_time) AS tried
FROM
ftplogview AS a
LEFT JOIN
palmtecsetup AS b ON a.Branch_code = b.Branch_code
WHERE
ftp_start_date = '2016-03-31'
GROUP BY
a.Branch_code, b.DevCount
ORDER BY
Branch_code
这是我到目前为止使用的查询...任何人都可以帮助我吗?
答案 0 :(得分:0)
我会使用公用表表达式
with cte(Branch_code, DevCount, total,ftp_start_time,ftp_stop_date,ftp_stop_time )
as (
SELECT
a.Branch_code,
b.DevCount,
a.ftp_start_time,
a.ftp_stop_date,
a.ftp_stop_time
FROM
ftplogview AS a
LEFT JOIN
palmtecsetup AS b ON a.Branch_code = b.Branch_code
GROUP BY
a.Branch_code, b.DevCount
)
SELECT Branch_code,
DevCount AS total,
COUNT(ftp_start_time) AS tried,
SUM(
case
when ftp_start_time is not null and ftp_stop_time is not null then 1
else 0 end
) as success,
SUM(
case
when ftp_stop_time is null then 1
else 0 end
) as failed
FROM CTE
WHERE ftp_start_time = '2016-03-31'
答案 1 :(得分:0)
希望这个会帮助你,使用下面的子选择查询 -
SELECT
q.Branch_code,
q.DevCount AS total,
COUNT(q.ftp_start_time) AS tried,
SUM(Success) AS SuccessCount,
SUM(Failed) AS FailedCount,
SUM(NOTTRIED) AS NOTTRIEDCount
FROM
(
SELECT
a.Branch_code,
b.DevCount AS total,
a.ftp_start_time AS tried,
CASE WHEN a.ftp_start_time IS NOT NULL AND a.ftp_stop_time IS NOT NULL THEN 1 ELSE 0 END AS Success,
CASE WHEN a.ftp_start_time IS NOT NULL AND a.ftp_stop_time IS NULL THEN 1 ELSE 0 END AS Failed,
CASE WHEN a.ftp_start_time IS NULL AND a.ftp_stop_time IS NULL THEN 1 ELSE 0 END AS NOTTRIED
FROM
ftplogview AS a
LEFT JOIN
palmtecsetup AS b ON a.Branch_code = b.Branch_code
WHERE
ftp_start_date = '2016-03-31'
) Q
GROUP BY
Q.Branch_code, Q.Total
ORDER BY
Q.Branch_code