TSQL-汇总SQL 2005

时间:2009-10-20 23:12:06

标签: sql sql-server sql-server-2005 tsql

我有以下示例代码:

create table Details(
  name varchar(20),
  age int,
  weight int,
  recordDate Datetime)

--insert data

..查询:

SELECT a.name,
       a.age,
       a.recordDate,
       a.weight - (SELECT b.weight
                     FROM Details
                    WHERE b.recordDate = dateadd(dd, -1, a.recordDate) as subtable)                             
  FROM Details a
GROUP BY WITH ROLLUP (a.recordDate, a.name, a.age)

我希望看到每个人的RecordDates之间的重量差异,然后记录该人和年龄组的不同总重量,然后记录重量增加/减少。这不是我的实际表格,只是一个例子。

问题: 它抱怨子查询 - 然后我不得不将它用作表变量:subtable。

现在它在抱怨:

Msg 156, Level 15, State 1, Line 14
Incorrect syntax near the keyword 'as'.
Msg 319, Level 15, State 1, Line 18
Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon.

我错过了什么?

5 个答案:

答案 0 :(得分:2)

错字:

a.weight - (SELECT b.weight
              FROM Details
             WHERE b.recordDate = dateadd(dd, -1, a.recordDate)

...“b”被用作表别名,但它实际上并没有被定义为一个。

下一个问题是您的GROUP BY 包含a.weight,并且没有与之关联的聚合函数。这是我对您的查询的重写:

  SELECT a.name,
         a.age,
         a.recordDate,
         SUM(a.weight - t.weight) 'weight'
    FROM DETAILS a
    JOIN (SELECT b.recordDate,
                 b.weight
            FROM DETAILS b) t ON t.recordDate = DATEADD(dd, -1, a.recordDate)
GROUP BY (a.recordDate, a.name, a.age) WITH ROLLUP

答案 1 :(得分:1)

不要使用AS关键字。你可以直接写{{select * from blah)a}

答案 2 :(得分:1)

尝试这样

SELECT
    a.name,
    a.age,
    a.recordDate,
    SUM(a.weight - b.weight) as WeightDiff
FROM Details a
JOIN Details b 
    ON (b.age        = a.age
    AND b.name       = a.name
    AND b.recordDate = dateadd(dd, -1, a.recordDate)
        )
GROUP BY a.age, a.name, a.recordDate WITH ROLLUP 

答案 3 :(得分:0)

好的,问题是WITH ROLLUP并不是你想要的答案。这是用于创建小计而非运行总计这是您所追求的,因此使用它将为您提供不同日期组合的总数,而不是运行总计,是你所追求的。在一开始,您希望得到的总数与您的姓名,年龄,日期和体重相比,与昨天相比的查询如下:

select
      a.name
     ,a.age
     ,a.recordDate
     ,(SELECT b.weight from Details b WHERE b.recordDate = dateadd(dd,-1,a.recordDate)) - a.weight as weightLossForToday
   from details a

请记住,只有每天只有1条记录才能使用此查询。如果您有一天的2条记录或条目不完全相隔1天(即它们包括时间),那么它将无效。为了让总体工作变得有效,您需要按照this之类的问题来处理这种方法。

这应该可以解决问题。

答案 4 :(得分:-1)

SELECT a.name,a.age,a.recordDate,a.weight-(SELECT b.weight
                                           FROM Details
                                           WHERE b.recordDate=dateadd(dd,-1,a.recordDate))
FROM Details a
GROUP BY (a.recordDate,a.name,a.age)
WITH ROLLUP