SQL Server:在选择列表中用别名乘以列

时间:2018-08-24 14:00:39

标签: sql sql-server sql-server-2008 select multiplying

我的查询中有一个选择列表,如下所示:

SELECT 
    COUNT(*) OVER () AS TotalRowsFound,
    MIN(t.Title) AS Title,
    t.ItemID, ' + @selectedColumn + ' as SelectedColumnSales ' + ', 
    t.CurrentPrice,
    (t.CurrentPrice * t.SelectedColumnSales) as TotalRevenuePerItem
FROM 
    dbo.SearchedUserItems t

我遇到问题的查询部分如下:

  (t.CurrentPrice * t.SelectedColumnSales) as TotalRevenuePerItem

在选择列表中...根据我传递给查询的内容,“ SelectedColumnSales”可以是不同的列,如下所示:

DECLARE @selectedColumn NVARCHAR(500)

    IF(@SelectedRange=7)
       SET @selectedColumn = 't.SevenDaySales'
    ELSE IF (@SelectedRange=14)
       SET @selectedColumn='t.FourteenDaySales'
    ELSE IF (@SelectedRange=21)
       SET @selectedColumn='t.TwentyOneDaySales'
    ELSE IF (@SelectedRange=30)
       SET @selectedColumn='t.ThirtyDaySales'

现在要获得每件商品的收入列,我需要像上面那样将这两者相乘,但是查询会引发此错误:

  

内部异常:SqlException:无效的列名'SelectedColumnSales'。

如何在选择列表中将动态列与静态列相乘?

有人可以帮我吗?

4 个答案:

答案 0 :(得分:2)

如果您要编写一个动态查询,看起来就像是,只需将变量放在等式中

 declare @sql nvarchar(max)
 set @sql = 'select 
    COUNT(*) OVER () AS TotalRowsFound,
        MIN(t.Title) AS Title
        , t.ItemID
        ,' + @selectedColumn + ' as SelectedColumnSales ' + 
        ', t.CurrentPrice
         , (t.CurrentPrice * ' + @selectedColumn + ') as TotalRevenuePerItem

    FROM 
        dbo.SearchedUserItems t'
exec(@sql)

答案 1 :(得分:1)

也许通过用户选择的索引并使用CHOOSE()

我们假设:

Item               Index
SevenDaySales      0
FourteenDaySales   1
TwentyOneDaySales  2
ThirtyDaySales     3

那么你可以

SELECT COUNT(*) OVER () AS TotalRowsFound
      ,MIN(t.Title) AS Title
      ,t.ItemID
      ,choose(@Index+1,t.SevenDaySales,t.FourteenDaySales,t.TwentyOneDaySales,t.ThirtyDaySales) as SelectedColumnSales  
      ,t.CurrentPrice
      ,(t.CurrentPrice * choose(@Index+1,t.SevenDaySales,t.FourteenDaySales,t.TwentyOneDaySales,t.ThirtyDaySales)) as TotalRevenuePerItem
 FROM  dbo.SearchedUserItems t

如果您不想传递索引,而不想传递@Index+1,则可以@SelectedRange/7

答案 2 :(得分:0)

您可以尝试使用case子句

直接在查询中使用登录名来代替字符串concat
 SELECT 
    COUNT(*) OVER () AS TotalRowsFound,
        MIN(t.Title) AS Title
        , t.ItemID
        , case when @SelectedRange=7 then t.SevenDaySales 
              when @SelectedRange=14 then t.FourteenDaySales
              when @SelectedRange=21 then t.TwentyOneDaySales
              when (@SelectedRange=30 then t.ThirtyDaySales end 
         as SelectedColumnSales  
        , t.CurrentPrice
         , (t.CurrentPrice * t.SelectedColumnSales) as TotalRevenuePerItem

    FROM 
        dbo.SearchedUserItems t

答案 3 :(得分:0)

将查询包装在派生表中,然后可以引用它之外的那些列:

select dt.TotalRowsFound, dt.Title, ... ,
      (dt.CurrentPrice * dt.SelectedColumnSales) as TotalRevenuePerItem
from
(
  SELECT 
    COUNT(*) OVER () AS TotalRowsFound,
        MIN(t.Title) AS Title
        , t.ItemID
        ,' + @selectedColumn + ' as SelectedColumnSales ' + 
        ', t.CurrentPrice
    FROM 
        dbo.SearchedUserItems t
) dt