Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从下拉列表中减去值_Sql - Fatal编程技术网

Sql 从下拉列表中减去值

Sql 从下拉列表中减去值,sql,Sql,我被一些SQL难住了,如下所示 我有两个dropdownlist,让用户选择日期,下面是SQL: SELECT * FROM [CountTable] WHERE (([Date] = @Date) OR ([Date] = @Date2)) 结果: Date UserID Count 18/12/2013 User1 100 19/12/2013 User1 105 19/12/2013 User2 10 现在,我想要一个SQL命令来计算两个日期之间的计数

我被一些SQL难住了,如下所示

我有两个dropdownlist,让用户选择日期,下面是SQL:

SELECT * FROM [CountTable] WHERE (([Date] = @Date) OR ([Date] = @Date2))
结果:

Date        UserID  Count
18/12/2013  User1   100
19/12/2013  User1   105
19/12/2013  User2   10
现在,我想要一个SQL命令来计算两个日期之间的计数。 如果用户ID相同,则新计数减去旧计数。 如果在旧日期中找不到用户ID,则它将保留新计数

我想要的结果如下:

UserID   Counter
User1    5
User2    10

假设要从
@Date2
记录中减去
@Date
记录,可以执行以下操作:

SELECT 
  UserID,
  SUM(
    CASE
      WHEN [DATE] = @Date2 THEN Count
      ELSE -1*Count
    END
   ) AS Counter
FROM [CountTable]
WHERE (([Date] = @Date) OR ([Date] = @Date2))
GROUP BY UserID

无论date1是在date2之前还是之后(反之亦然),这都应该有效:

选择userid,
总数(例)
当[Date]=@Date2和@Date2>@Date1时
[计数]
当[Date]=@Date2和@Date2<@Date1时
-[计数]
当[Date]=@Date1和@Date1>@Date2时
[计数]
当[Date]=@Date1和@Date1<@Date2时
-[计数]
(完)作为计数器
从[可数表]
其中(([Date]=@Date)或([Date]=@Date2))
按用户ID分组

谢谢你的帮助,你回答了我的问题。
select userid,
       sum(case
             when [ Date ] = @Date2 and @Date2 > @Date1 then
              [ Count ]
             when [ Date ] = @Date2 and @Date2 < @Date1 then
              - [ Count ]
             when [ Date ] = @Date1 and @Date1 > @Date2 then
              [ Count ]
             when [ Date ] = @Date1 and @Date1 < @Date2 then
              - [ Count ]
           end) as counter
  from [ CountTable ]
 where (([ Date ] = @Date) OR ([ Date ] = @Date2))
 group by userid