如何用条件求和多个收益?

时间:2014-04-12 15:57:09

标签: sql sql-server tsql

enter image description here

我的剧本:

USE Cars

DECLARE @TotalMoneyForService money; 
DECLARE @CurrentDate date; 
DECLARE @DateCompleted date;

SET @CurrentDate =  GETDATE();

SET @DateCompleted = (SELECT DateCompleted 
    FROM ServiceType 
    WHERE DateCompleted =  @CurrentDate);

SET @TotalMoneyForService = (SELECT SUM(Price)  
    FROM ServiceType    
    WHERE DateCompleted = @CurrentDate);

PRINT @CurrentDate; 
IF  @TotalMoneyForService > 0 AND  @DateCompleted = @CurrentDate     
    PRINT 'Today Total Car Maintenance is $' +   
    CONVERT(varchar,@TotalMoneyForService,1); 
ELSE    
    PRINT 'No Car Expense Maintenance Today' ;

1 CASE OUTPUT:

2014-04-12
Today Total Car Maintenance is $43.00

2案例输出: 我在这里有问题,如果我们在字段中说DateCompleted我会有两个相同日期的单元格,让我们说,2014-04-12我会有结果:

  

Msg 512,Level 16,State 1,Line 9
  子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   一种表达。 2014-04-12今日没有汽车费用维修

如果DateCompleted =当前日期,我想获得Price字段的总和,所以在第二种情况下它应该是53.00 我知道我有多个返回,并且我的@DateCompleted包含两个结果,如数组?我有点困惑,如果有人能指导我,告诉我我做错了什么,真的很感激。 谢谢你的时间。

2 个答案:

答案 0 :(得分:0)

您可以尝试:

DECLARE @TotalMoneyForService money; 
DECLARE @CurrentDate date; 
DECLARE @DateCompleted date;

SET @CurrentDate =  CONVERT(DATETIME,CONVERT(VARCHAR(12), GETDATE()));

;with TotMaint
AS
(
SELECT
    SUM(Price) AS Price
FROM
    ServiceType
where
    CONVERT(DATETIME,CONVERT(VARCHAR(12), DateCompleted)) =  @CurrentDate
)
select  
    case when Price is null THEN 'No Car Expense Maintenance Today'
    else 'Today Total Car Maintenance is $' + convert(varchar(10), Price)
    end as [Answer]
from
    TotMaint

答案 1 :(得分:0)

更改此行代码

SET @DateCompleted = (SELECT top 1 DateCompleted 
    FROM ServiceType 
    WHERE DateCompleted =  @CurrentDate);