如果未使用EXISTS引入子查询,则只能在选择list.error中指定一个表达式。不知道怎么做if exists语句。
SELECT DISTINCT
t1.id,t1.scn,t1.vsl_name,case when t1.id = t1.id THEN 'IMPORT' ELSE '0' END AS import_export,
dbo.fn_format_datetime(t1.act_arr_dt_tm) AS act_arr_dt_tm,
dbo.fn_format_datetime(t1.act_dept_dt_tm) AS act_dept_dt_tm,
( SELECT t1.scn, COUNT(t1.id) AS total_count_bl_status_c
FROM ccosbl t1
INNER JOIN vesvoy t2 ON t2.scn= t1.scn
WHERE t1.status_ind= 'C'
GROUP BY t1.scn)
FROM vesvoy t1
INNER JOIN ccosbl t2 ON t2.scn = t1.scn
WHERE t2.status_ind = 'C'
GROUP BY t1.scn,t1.vsl_name,t1.act_arr_dt_tm,t1.act_dept_dt_tm,t1.id
我需要将select语句合二为一。在sql中还有其他方法吗?
答案 0 :(得分:0)
如果您坚持使用相关子查询,那么您需要确保选择中只包含一列:
SELECT DISTINCT
t1.id,t1.scn,t1.vsl_name,case when t1.id = t1.id THEN 'IMPORT' ELSE '0' END AS import_export,
dbo.fn_format_datetime(t1.act_arr_dt_tm) AS act_arr_dt_tm,
dbo.fn_format_datetime(t1.act_dept_dt_tm) AS act_dept_dt_tm,
( SELECT COUNT(t4.id) AS total_count_bl_status_c
FROM ccosbl t4
INNER JOIN vesvoy t5 ON t4.scn= t5.scn
WHERE t1.status_ind= 'C' and t4.scn = t2.scn)
FROM vesvoy t1
INNER JOIN ccosbl t2 ON t2.scn = t1.scn
WHERE t2.status_ind = 'C'
GROUP BY t1.scn,t1.vsl_name,t1.act_arr_dt_tm,t1.act_dept_dt_tm,t1.id
但是,更好的方法是使用带有连接的子查询:
SELECT DISTINCT
t1.id,t1.scn,t1.vsl_name,case when t1.id = t1.id THEN 'IMPORT' ELSE '0' END AS import_export,
dbo.fn_format_datetime(t1.act_arr_dt_tm) AS act_arr_dt_tm,
dbo.fn_format_datetime(t1.act_dept_dt_tm) AS act_dept_dt_tm,
t3.total_count_bl_status_c
FROM vesvoy t1
INNER JOIN ccosbl t2 ON t2.scn = t1.scn
LEFT JOIN
( SELECT t4.scn, COUNT(t4.id) AS total_count_bl_status_c
FROM ccosbl t4
INNER JOIN vesvoy t5 ON t4.scn= t5.scn
WHERE t4.status_ind= 'C'
GROUP BY t4.scn) t3
ON t2.scn = t3.scn
WHERE t2.status_ind = 'C'
GROUP BY t1.scn,t1.vsl_name,t1.act_arr_dt_tm,t1.act_dept_dt_tm,t1.id
答案 1 :(得分:0)
试试这个:
SELECT t3.id t3.scn,total_count_bl_status_c,act_arr_dt_tm,act_dept_dt_tm,vsl_name,case when t3.id = t3.id THEN 'IMPORT' ELSE '0' END AS import_export,
dbo.fn_format_datetime(t3.act_arr_dt_tm) AS act_arr_dt_tm,
dbo.fn_format_datetime(t3.act_dept_dt_tm) AS act_dept_dt_tm from
(SELECT t2.scn, COUNT(t2.id) AS total_count_bl_status_c
FROM ccosbl t1
INNER JOIN
vesvoy t2
ON t2.scn= t1.scn
WHERE t1.status_ind= 'C'
GROUP BY t1.scn)as t3
inner join
(SELECT * from ccosbl) as t4 on
ON t4.scn = t3.scn