问题是:创建一个脚本,计算并打印所有购买的总和。
标记规则还说我们必须在答案中使用DECLARE
和IF
语句
输出必须如下所示:
示例结果:
(2行(s)受影响)
昂贵产品总和:5998.00
这是一个学校作业,所以我不期待一个完整的答案,只是推动正确的方向,因为我不知道为什么这不会起作用。
我正在使用SQL Server Management Studio 2014
这是我到目前为止所得到的:
DECLARE @SUM_OF_EXPENSIVE_PRODUCTS int, @SUM_OF_AVERAGE_PRODUCTS int, @SUM_OF_CHEAP_PRODUCTS int
IF ((SELECT Price AS EXPENSIVE_PRODUCT FROM Product WHERE Price > 2000 ) > 0)
SELECT SUM(EXPENSIVE_PRODUCT) = @SUM_OF_EXPENSIVE_PRODUCTS
ELSE IF ((SELECT Price AS AVERAGE_PRODUCT FROM Product WHERE Price > 1000) > 0)
SELECT SUM(AVERAGE_PRODUCT) = @SUM_OF_AVERAGE_PRODUCTS
ELSE IF ((SELECT Price AS CHEAP_PRODUCT FROM Product WHERE Price < 1000) > 0)
SELECT SUM(CHEAP_PRODUCT) = @SUM_OF_CHEAP_PRODUCTS
ELSE
SELECT 'NO PRODUCTS EXIST'
答案 0 :(得分:1)
试试这个,
更新了查询
BEGIN
DECLARE @ResultText varchar(100)
DECLARE @Result varchar(10)
IF EXISTS(Select 1 from tempTable WHERE Price > 1999)
BEGIN
SET @ResultText = 'SUM_OF_EXPENSIVE_PRODUCTS : '
SET @Result = (SELECT SUM(Price) from tempTable where Price > 1999)
SET @ResultText = @ResultText + @Result
END
ELSE IF EXISTS(Select 1 from tempTable WHERE Price > 999)
BEGIN
SET @ResultText = 'SUM_OF_AVERAGE_PRODUCTS : '
SET @Result = (SELECT SUM(Price) from tempTable where Price > 999)
SET @ResultText = @ResultText + @Result
END
ELSE IF EXISTS(Select 1 from tempTable WHERE Price > 0)
BEGIN
SET @ResultText = 'SUM_OF_AVERAGE_PRODUCTS : '
SET @Result = (SELECT SUM(Price) from tempTable where Price > 0)
SET @ResultText = @ResultText + @Result
END
ELSE
BEGIN
SET @ResultText = 'NO PRODUCTS EXIST'
END
SELECT @ResultText
END