-2

我有一个查询:

SELECT   [outer].*,
         (total_pain_patients / NULLIF ((SELECT Sum(total_pain_patients)
             FROM   [topplansperprovider]
             WHERE  [outer].[INDEX_IMSID] = [INDEX_IMSID]
             AND plan_rank BETWEEN 1 AND 10), 0)) * 100 AS PercentOf,
         pm.*,
         percentof * pm.score
FROM     [topplansperprovider] AS [outer]
left JOIN [payer Mapping] pm
on lower([outer].Plan_Name_OR_Payment_Type)=lower(pm.[ims payer name])
WHERE    INDEX_IMSID = '1753841'
ORDER BY 6 ASC

我的问题是选择这个:

percentof * pm.score

由于percentof是派生列的别名,我不知道如何在其他列中使用它。

  1. 我该如何选择percentof * pm.score
  2. 如果这太难了,我怎样才能将percentof作为永久列添​​加到我的表中?
4

3 回答 3

6

您不能使用这样的别名,您必须将查询包装在另一个选择中:

select x.*, x.percentof*x.pm.score newvalue
from
(
    SELECT   [outer].*,
             (total_pain_patients / NULLIF ((SELECT Sum(total_pain_patients)
                                             FROM   [topplansperprovider]
                                             WHERE  [outer].[INDEX_IMSID] = [INDEX_IMSID]
                                                    AND plan_rank BETWEEN 1 AND 10), 0)) * 100 PercentOf,
             pm.*
    FROM     [topplansperprovider] AS [outer]
    left JOIN [payer Mapping] pm
        on lower([outer].Plan_Name_OR_Payment_Type)=lower(pm.[ims payer name])
) x
WHERE    x.INDEX_IMSID = '1753841'
ORDER BY 6 ASC

您正在计算的列别名percentof不可用于另一列,除非它在子查询中使用。

于 2012-09-11T20:44:16.380 回答
3

创建视图:

CREATE VIEW dbo.whatever
AS 
    SELECT 
      t.*, -- NAME THESE COLUMNS!!!
      PercentOf = (t.total_pain_patients / NULLIF ((SELECT Sum(t2.total_pain_patients)
         FROM   dbo.[topplansperprovider] AS t2
         WHERE  t2.[INDEX_IMSID] = t.[INDEX_IMSID]
         AND t2.plan_rank BETWEEN 1 AND 10), 0)) * 100,
      pm.* -- NAME THESE COLUMNS!!!
  FROM dbo.[topplansperprovider] AS t
  LEFT OUTER JOIN dbo.[payer Mapping] AS pm
  ON LOWER(t.Plan_Name_OR_Payment_Type) = LOWER(pm.[ims payer name])
  WHERE t.INDEX_IMSID = '1753841';
GO

现在您的查询可以是:

SELECT *, [something] = PercentOf * score -- NAME THIS ALIAS!
  FROM dbo.whatever
  ORDER BY 6 ASC; -- NAME THIS COLUMN!!!

但是,请停止使用惰性SELECT *语法,尤其是在视图中:

停止使用ORDER BY [ordinal]

这些都是最终会导致你痛苦的坏习惯。

于 2012-09-11T21:02:22.993 回答
1

虽然不是最佳答案,但您可以创建一个视图以在视图中具有“永久”列。

于 2012-09-11T20:42:53.803 回答