0

寻找一种更好的方法来编写这个查询,我的 SQL 技能不是很好,基本真的所以寻找任何指针来使它更好。这只是前两列,完整报告还有 10 列。

我正在采用一组特定的维修类型,并通过计数和计算对它们进行分析。第一个是提前到本财政年度的工作,第二个是当前收到的工作总数。

SELECT
    "Type",
    (
        SELECT
            NVL (COUNT(jjo.jjobno), 0)
        FROM
            jjobh jjo
        WHERE
            jjo.jclcode = 'L'
        AND jjo.jstatus <> '6'
        AND jjo.year_rec <> (
            SELECT
                sub_code
            FROM
                code_table
            WHERE
                main_code = 'YEAR'
        )
        AND (
            week_comp IS NULL
            OR year_comp = (
                SELECT
                    sub_code
                FROM
                    code_table
                WHERE
                    main_code = 'YEAR'
            )
        )
        AND jjo.jrepair_type = "Type"
    ) AS "B/F",
    (
        SELECT
            NVL (COUNT(jjo.jjobno), 0)
        FROM
            jjobh jjo
        WHERE
            jjo.jclcode = 'L'
        AND jjo.jstatus <> '6'
        AND jjo.year_rec = (
            SELECT
                sub_code
            FROM
                code_table
            WHERE
                main_code = 'YEAR'
        )
        AND jjo.jrepair_type = "Type"
    ) AS "Recvd"
FROM
    (
        SELECT
            rep.repair_type_code AS "Type"
        FROM
            repair_type rep
        WHERE
            rep.client = 'L'
        AND rep.work_centre = '004682'
        ORDER BY
            rep.repair_type_code
    )
ORDER BY
    "Type";
4

1 回答 1

0

你的代码是一团糟。我怀疑你想要类似的东西:

SELECT jjo.jrepair_type, count(*) as valbf
FROM (SELECT coalesce(COUNT(jjo.jjobno), 0)
      FROM jjobh jjo cross join
           (SELECT sub_code
            FROM code_table
            WHERE main_code = 'YEAR'
           ) sc
      WHERE jjo.jclcode = 'L' AND
            jjo.jstatus <> '6' AND
            jjo.year_rec <> sc.sub_code AND
            (week_comp IS NULL OR
             year_comp = sc.sub_code
            ) 
     ) jjo join
     (SELECT rep.repair_type_code AS "Type"
      FROM repair_type rep
      WHERE rep.client = 'L' AND
            rep.work_centre = '004682'
     ) rtc
     on jjo.jrepair_type = rtc.repair_type_code
group by jjo.jrepair_type;

看起来您想将“jjo”表连接到“修复类型代码”表,生成有关每种修复类型的信息。子查询中的 order by 是没用的。

我的建议是将“jjo”表移到外部“from”。您还应该将 WHERE 子句移到最外面的 WHERE 子句(我没有这样做)。我还没有完全弄清楚日期逻辑,但这可能会让你走上正轨。

于 2012-07-31T12:58:54.233 回答