I have this sql (below) written by a previous developer. How can I break it up into three or four parts and join it together again instead of this single big sql? Please advise. I’m really new to sql and no idea how to simplify it. Thanks. I’m using C# console application.
SELECT distinct
department_name CTG_DEPARTMENT,
chart_id SPC_CHART_ID,
concat(process_id, concat('-', item_name)) MONITOR_ITEM,
product_id CTG_PRODUCT,
graphtype SPC_GRAPH_TYPE,
CASE WHEN viorules LIKE '%9%' THEN 'OOS'
WHEN viorules LIKE '%10%' THEN 'OOS'
WHEN viorules IS NULL THEN 'OK'
ELSE 'OOC' END SPC_STATUS,
process_stage,
'L8B' fab_name
FROM
(
SELECT
'ARRAY' process_stage,
dept.item_name department_name,
dept.chart_id,
proc_id.item_name process_id,
item.item_name,
product.item_name product_id,
graphtype
FROM
(
SELECT
item_name,
chart_id
FROM
aryspch.c_ctg_filter f,
aryspch.c_ctg_item i,
aryspch.c_ctg_relate r
WHERE
GROUP_ID = 6
AND filter_name IN ('Department')
AND f.filter_id = i.filter_id
AND i.item_id = r.item_id
) dept
,
(
SELECT
item_name,
chart_id
FROM
aryspch.c_ctg_filter f,
aryspch.c_ctg_item i,
aryspch.c_ctg_relate r
WHERE
GROUP_ID = 6
AND filter_name IN ('Process_ID')
AND f.filter_id = i.filter_id
AND i.item_id = r.item_id
) proc_id
,
(
SELECT
item_name,
chart_id
FROM
aryspch.c_ctg_filter f,
aryspch.c_ctg_item i,
aryspch.c_ctg_relate r
WHERE
GROUP_ID = 6
AND filter_name IN ('Item')
AND f.filter_id = i.filter_id
AND i.item_id = r.item_id
) item
,
(
SELECT
item_name,
chart_id
FROM
aryspch.c_ctg_filter f,
aryspch.c_ctg_item i,
aryspch.c_ctg_relate r
WHERE
GROUP_ID = 6
AND filter_name IN ('Product')
AND f.filter_id = i.filter_id
AND i.item_id = r.item_id
) product
,
(
SELECT DISTINCT
chartid,
graphtype
FROM
aryspch.spchis
WHERE
reporttime > SYSDATE - 2
) a
WHERE
dept.chart_id = proc_id.chart_id
AND dept.chart_id = item.chart_id
AND dept.chart_id = product.chart_id
AND dept.chart_id = a.chartid
)
spc
LEFT JOIN
(
SELECT
viorules,
mtimestamp,
chartid
FROM
aryspch.oochis
)
oochis
ON spc.chart_id = oochis.chartid
AND mtimestamp > SYSDATE - 2
One option is to use Common Table Expressions to define each sub-query, and then to join those named queries together.