case结果在同一查询中使用

时间:2011-11-29 14:14:20

标签: sql sql-server-2008 ssrs-2008

我正在尝试做类似的事情,但不知道如何在SQL查询中执行此操作。我首先创建列,然后想要删除列,因为它是一个计算列,我总是学习不使用表中的计算列

Alter table baseSupple add Buys int null
GO
select com.YrAmount, Buys = 
case when b.BaseAmount is null
   then com.Amount+ com.BaseAmount+ com.Amount1
   when b.BaseAmount is not null
   then com.Amount+ com.Amount1+ b.BaseAmount 
END, Sum(b.Buys - com.Tng) as Fy11, Sum(b.Buys - com.Tng - com.Tng) as Fy12  from baseSupple as b inner join comSupple as com on com.id = b.id
GO
Alter table baseSupple drop Buys

我以为我可以使用case语句执行此操作,但它会给我一个错误,因为无效的列名称因为它在同一语句中而无法识别。我假设我可以让这个工作,我可以复制并粘贴报告在一个report.rdl文件中的sql我是sql server报告服务器的新手,所以不确定这是否是在sql中生成这种类型的报告的正确方法服务器商业智能开发工作室

3 个答案:

答案 0 :(得分:1)

由于这似乎是您要运行的报告的基础,我可能会在您的基表上创建一个视图:

-- create a view as the data source for your report
CREATE VIEW dbo.baseSuppleView AS
  -- create a CTE to determine the "Buys" column
  WITH BuysCTE AS
  (
      SELECT 
          com.YrAmount,
          com.Tng,
          Buys = CASE 
                    WHEN b.BaseAmount IS NULL
                       THEN com.Amount + com.BaseAmount + com.Amount1
                    ELSE
                      com.Amount + com.Amount1 + b.BaseAmount 
                 END 
      FROM dbo.baseSupple AS b 
      INNER JOIN dbo.comSupple AS com ON com.id = b.id
  )
  SELECT   -- select from that CTE - now defined, you can use the "Buys" column
      YrAmount, 
      Buys, 
      SUM(Buys - Tng) AS Fy11, 
      SUM(Buys - 2 * Tng) AS Fy12  
  FROM BuysCTE
  GROUP BY YrAmount, Buys  -- when you have SUM(....), you need GROUP BY(....)

然后只需使用此视图作为报告的来源。

由于该列的计算是在视图定义中完成的,因此您的基表及其性能决不受此计算列的影响,您不必在表中不断创建和删除列...

答案 1 :(得分:0)

不知道你为什么需要改变表..

Select yrAmount, SUM(Buys-tng) as FY11, Sum(buys-tng-tng) as FY12
FROM (
select com.YrAmount, 
case when b.BaseAmount is null
  then com.Amount+ com.BaseAmount+ com.Amount1
  when b.BaseAmount is not null
  then com.Amount+ com.Amount1+ b.BaseAmount END as buys
FROM baseSupple b
INNER JOIN comSupple com 
 on com.id = b.id) A

编辑:忘了从子查询中购买。

答案 2 :(得分:0)

无需任何DDL更改即可获得所需的计算结果。我想下面的一个应该有效。

`SELECT com.YrAmount, 
     CASE when b.BaseAmount is null
        then com.Amount+ com.BaseAmount+ com.Amount1
        when b.BaseAmount is not null
        then com.Amount+ com.Amount1+ b.BaseAmount 
     END as Buys,
     Sum(b.Buys - com.Tng) as Fy11, 
     Sum(b.Buys - com.Tng - com.Tng) as Fy12
FROM baseSupple as b inner join comSupple as com
   on com.id = b.id
GO`

此致 Venk