1

我有列 ID,USERSID 表的用户表:

  t_A(ID,usersID,ADATE,priceA,priceB)
  t_B(ID,usersID,BDATE,priceA,priceB)
  t_C(ID,usersID,CDATE,priceA,priceB)

我正在使用此查询从 X DATE 和 USERSID 的 3 个表中获取价格总和

    declare @id int 
    set @id = 3 -- for example 

    SELECT SUM(priceA) as TA, SUM(priceB) as TB
    FROM  t_A,t_B,t_C
    WHERE  t_A.USERSID =  @id
    AND     t_B.USERSID =  @id
    AND     t_C.USERSID =  @id
    AND    ADATE >= DATEADD(DAY, 0, DATEDIFF(DAY, 0, getdate())) 
   AND     BDATE >= DATEADD(DAY, 0, DATEDIFF(DAY, 0, getdate())) 
   AND    CDATE >= DATEADD(DAY, 0, DATEDIFF(DAY, 0, getdate())) 

此脚本仅在用户 ID 在三个表中有一行时才有效,否则脚本不返回任何内容

4

3 回答 3

1

因为如果只有一张表没有 USERID = 3,那么结果总是空的。解决方法:将选项与UNION ALL运算符一起使用

DECLARE @id int 
SET @id = 3
SELECT SUM(x.priceA) as TA, SUM(x.priceB) AS TB
FROM (
      SELECT priceA, priceB
      FROM t_A 
      WHERE t_A.USERSID =  @id
        AND ADATE >= DATEDIFF(d,0,dateadd(d,0,getdate()))
      UNION ALL
      SELECT priceA, priceB
      FROM t_B 
      WHERE t_B.USERSID =  @id
        AND BDATE >= DATEDIFF(d,0,dateadd(d,0,getdate()))
      UNION ALL   
      SELECT priceA, priceB
      FROM t_C 
      WHERE t_C.USERSID =  @id
        AND CDATE >= DATEDIFF(d,0,dateadd(d,0,getdate()))
      ) x
于 2013-04-15T12:55:02.103 回答
0

您无法将日期列与 datediff 进行比较。以下是您可以做的一些事情:

AND ADATE >= GETDATE()

或者:

AND DATEDIFF(d, ADATE, GETDATE()) > 1

您可以在 MSDN 上查看语法和一些示例。

于 2013-04-15T12:47:59.707 回答
0

我认为这就是你所需要的。这样,只要其中一个表满足条件,它就会返回结果:

SELECT SUM(priceA) as TA, SUM(priceB) as TB, SUM(priceC) as TC
    FROM  t_A
    FULL JOIN t_B
    FULL JOIN t_C
    WHERE  t_A.USERSID =  @id
    AND     t_B.USERSID =  @id
    AND     t_C.USERSID =  @id
    AND    ADATE >= DATEDIFF(d,0,dateadd(d,0,getdate()))
   AND     BDATE >= DATEDIFF(d,0,dateadd(d,0,getdate()))
   AND    CDATE >= DATEDIFF(d,0,dateadd(d,0,getdate()))
于 2013-04-15T12:54:35.623 回答