这个脚本sql有什么问题?

时间:2013-04-15 12:38:34

标签: sql sql-server-2005

我的表用户有列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())) 

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

AND ADATE >= GETDATE()

或:

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

您可以检查语法和some examples at MSDN.

答案 2 :(得分: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()))