缩短查询:每位医生每年成功注意的百分比

时间:2016-11-01 05:56:15

标签: sql sql-server

我正在使用以下视图:

enter image description here

它显示了每年给定医生成功注意的次数。

现在,我想创建一个查询,根据每年的分数(自雇用以来)给出成功关注的百分比。那是[1996年成功注意事项] / [总注意事项]

在某种程度上我完成了这件事,但我不喜欢我写的剧本:

SELECT tv1.Doc_ID, Y1996, Y1997, Y1998, Y1999, Y2000, Y2001
FROM
(
    SELECT  Doc_ID, CAST(1.00*[Successful 1996]/[Total Attentions] AS DECIMAL(10,2)) AS Y1996
    FROM VIEW3
) tv1,
(
    SELECT  Doc_ID, CAST(1.00*[Successful 1997]/[Total Attentions] AS DECIMAL(10,2)) AS Y1997
    FROM VIEW3
) tv2,
(
    SELECT  Doc_ID, CAST(1.00*[Successful 1998]/[Total Attentions] AS DECIMAL(10,2)) AS Y1998
    FROM VIEW3
) tv3,
(
    SELECT  Doc_ID, CAST(1.00*[Successful 1999]/[Total Attentions] AS DECIMAL(10,2)) AS Y1999
    FROM VIEW3
) tv4,
(
    SELECT  Doc_ID, CAST(1.00*[Successful 2000]/[Total Attentions] AS DECIMAL(10,2)) AS Y2000
    FROM VIEW3
) tv5,
(
    SELECT  Doc_ID, CAST(1.00*[Successful 2001]/[Total Attentions] AS DECIMAL(10,2)) AS Y2001
    FROM VIEW3
) tv6
WHERE tv1.doc_id=tv2.doc_id
AND tv1.doc_id=tv3.doc_id
AND tv1.doc_id=tv4.doc_id
AND tv1.doc_id=tv5.doc_id
AND tv1.doc_id=tv6.doc_id

我基本上每年都会创建单独的表,然后加入它们,但不得不重复查询的事实并不好看。我试图使用CASE ... THEN ... ELSE语句,但它给出了一个错误。

是CASE ......那么......是否可以编写更短的查询?是否是,我如何

2 个答案:

答案 0 :(得分:1)

如果您选择相同的视图,则可以一起选择它们,无需分割选择。

SELECT Doc_ID, 
CAST(1.00*[Successful 1996]/[Total Attentions] AS DECIMAL(10,2)) AS Y1996,
CAST(1.00*[Successful 1997]/[Total Attentions] AS DECIMAL(10,2)) AS Y1997,
CAST(1.00*[Successful 1998]/[Total Attentions] AS DECIMAL(10,2)) AS Y1998,
CAST(1.00*[Successful 1999]/[Total Attentions] AS DECIMAL(10,2)) AS Y1999,
CAST(1.00*[Successful 2000]/[Total Attentions] AS DECIMAL(10,2)) AS Y2000,
CAST(1.00*[Successful 2001]/[Total Attentions] AS DECIMAL(10,2)) AS Y2001
FROM VIEW3

答案 1 :(得分:0)

也许我在你的问题中遗漏了一些东西,但你所做的事情基本归结为:

SELECT
    doc_id,
    Y1996=CAST(1.00*[Successful 1996]/[Total Attentions] AS DECIMAL(10,2)),
    Y1997=CAST(1.00*[Successful 1997]/[Total Attentions] AS DECIMAL(10,2)),
    Y1998=CAST(1.00*[Successful 1998]/[Total Attentions] AS DECIMAL(10,2)),
    Y1999=CAST(1.00*[Successful 1999]/[Total Attentions] AS DECIMAL(10,2)),
    Y2000=CAST(1.00*[Successful 2000]/[Total Attentions] AS DECIMAL(10,2)),
    Y2001=CAST(1.00*[Successful 2001]/[Total Attentions] AS DECIMAL(10,2))
FROM
    VIEW3
ORDER BY
    doc_id;

也就是说,如果Doc_Id是主键或唯一索引(即每个Doc_Id在源表中最多只出现一次)。