在VIEW中编写此特定SELECT查询的更好方法

时间:2011-11-22 15:46:18

标签: sql select view case

我想知道在下面的查询中是否有更好的方法来编写SELECT子句。 status有三种可能的情况。它可以具有值'A'或'N'或null。

我认为在将subTable值与值'A'进行比较时,将AND status = 'A'放在where子句中是多余的。有没有办法可以更有效地重写?我觉得限制WHERE子句中的状态总是会给你一个'A',因此无需做CASE语句。

ALTER VIEW dbo.st_review_status_vw AS
(
    SELECT c.st_id, c.ms_price_comp_fy, 
        CASE
            WHEN (SELECT status FROM 
                    (SELECT st_id, status, ms_price_comp_fy
                     FROM ms_price_comp
                     WHERE st_id = c.st_id 
                         AND ms_price_comp_fy = c.ms_price_comp_fy 
                         AND status = 'A'
                     GROUP BY st_id, status, ms_price_comp_fy)
                 AS subTable) = 'A' THEN 'C'
            ELSE 'I'
        END AS status,
        MAX(date_approved) AS date_completed
    FROM ms_price_comp AS c
    GROUP BY c.st_id, c.ms_price_comp_fy
)

2 个答案:

答案 0 :(得分:3)

试试这个

ALTER VIEW dbo.st_review_status_vw AS (
SELECT c.st_id, c.ms_price_comp_fy, 

    CASE WHEN MIN(status)  = 'A' THEN 'C'
    ELSE 'I'
    END AS status,

MAX(date_approved) AS date_completed
FROM ms_price_comp AS c
GROUP BY c.st_id, c.ms_price_comp_fy
)

答案 1 :(得分:0)

这看起来和我一样

ALTER VIEW dbo.st_review_status_vw AS (
SELECT
        c.st_id
    ,   c.ms_price_comp_fy
    ,   CASE
            WHEN MIN(status) = 'A' THEN 'C'
            ELSE 'I'
        END AS status
    ,   MAX(date_approved) AS date_completed
FROM ms_price_comp AS c
GROUP BY c.st_id, c.ms_price_comp_fy
)