SUM一个值列表(包含子查询)

时间:2015-08-21 14:44:06

标签: sql sql-server sql-server-2012

我目前有一些代码可以获取最新的汇率并转换一个值列表,因为有些值已经是GBP,那么我正在使用CASE语句......

我的问题是如何总结以下查询:

DECLARE @cmd      NVARCHAR(250);
DECLARE @tOutput  TABLE(data NVARCHAR(50));
DECLARE @URL      NVARCHAR(100);

SET @URL= 'http://finance.yahoo.com/d/quotes.csv?f=l1&s=CADGBP=X'
SET @cmd = 'powershell "(new-object System.Net.WebClient).DownloadString('''+@URL+''')"'

INSERT @tOutput EXEC master.dbo.xp_cmdshell @cmd

select 
SUM(
CASE 
    WHEN (PartsDatabase.ManufacturerID = 38) 
    THEN ((((PartsDatabase.ListPrice * (1 - PartsDatabase.Discount)) * PartsDatabase.ShippingAndTaxes) + (PartsDatabase.ListPrice * (1 - PartsDatabase.Discount))) * (SELECT * FROM @tOutput WHERE data IS NOT NULL)) * PartsDatabase.StockQuantity
    ELSE PartsDatabase.ListPrice * PartsDatabase.StockQuantity
 END 
 )
 ListPrice
FROM PartsDatabase
where PartsDatabase.StockQuantity >0

如果我可以将此查询放入View中,那么它会很简单,但我很确定我不能在视图中使用DECLARE键,但我可能在这里错了

感谢您的帮助:D

要添加到下面的答案,我运行此代码以检索报告中的值:

DECLARE @value DECIMAL(10,3);
Exec TotalStockValue @ListPrice = @value  OUTPUT  

-- now the value is stored in @ListPrice variable do whatever you need to do with tit
SELECT @value AS [List Price]

1 个答案:

答案 0 :(得分:2)

CREATE PROCEDURE My_Proc
   @URL       NVARCHAR(250) = 'http://finance.yahoo.com/d/quotes.csv?f=l1&s=CADGBP=X'
  ,@ListPrice DECIMAL(10,3) OUTPUT 
AS
BEGIN
DECLARE @cmd      NVARCHAR(250);
DECLARE @tOutput  TABLE(data NVARCHAR(50));
DECLARE @Data     DECIMAL(10,5);

SET @cmd = 'powershell "(new-object System.Net.WebClient).DownloadString('''+@URL+''')"'

INSERT @tOutput EXEC master.dbo.xp_cmdshell @cmd

SELECT TOP 1 @Data = DATA FROM @tOutput WHERE data IS NOT NULL    

select @ListPrice = SUM(
                     CASE 
                        WHEN (PartsDatabase.ManufacturerID = 38) 
                        THEN ((((PartsDatabase.ListPrice * (1 - PartsDatabase.Discount)) 
                                  * PartsDatabase.ShippingAndTaxes) + (PartsDatabase.ListPrice * (1 - PartsDatabase.Discount))) 
                                     * (@Data)) * PartsDatabase.StockQuantity
                        ELSE PartsDatabase.ListPrice * PartsDatabase.StockQuantity
                     END 
                     )
FROM PartsDatabase
where PartsDatabase.StockQuantity >0

END

程序调用

你会把这个程序称为这样......

DECLARE @listPrice DECIMAL(10,3);
Exec My_Proc @ListPrice = @listPrice  OUTPUT  


-- now the value is stored in @ListPrice variable do whatever you need to do with tit
SELECT @listPrice AS [List Price]