SQL 2008:分组未正确返回我的数据

时间:2014-06-04 10:23:28

标签: sql-server-2008

我有一个查询,我写的是为了提取数据并对特定ID进行计数,我现在的问题是,而不是数据ruturning作为我的计数的单个状态行,它没有正确地对它们进行分组:

Select  ti.Status [Status]
      , (SELECT COUNT(*) FROM Local_Sent With(Nolock) Where ls.localID = LO.ID and ls.STID = 7) [Delivered]
      , (SELECT COUNT(*) FROM Local_Sent With(Nolock) Where ls.localID = LO.ID and ls.STID = 6) [Duplicate]
      , (SELECT COUNT(*) FROM Local_Sent With(Nolock) Where ls.localID = LO.ID and ls.STID = 10) [Error: Invalid]
      , (SELECT COUNT(*) FROM Local_Sent With(Nolock) Where ls.localID = LO.ID and ls.STID = 2) [Sent]
      , (SELECT COUNT(*) FROM Local_Sent With(Nolock) Where ls.localID = LO.ID and ls.STID = 9) [Undelivered]
From Local LO With(Nolock)
Inner Join Local_Sent ls With(Nolock)
    On LO.ID = ls.localID
Inner Join ls.StatusID SS
    ON ls.StatusID = SS.ID
Inner Join FileStatus FS
    On M.FileStatus = FS.ID
Where Convert(varchar,ls.LoDate,23) = DateAdd(day,-1, Convert(Varchar,GETDATE(),23))
Group By ti.Status, M.ID, ls.LoDate

返回结果


Status Of Matters Delivered Duplicate Error: Invalid Sent Undelivered Broken Files 28 5 0 0 7 Follow-up File 2 0 0 0 13 Broken Files 1 0 0 0 15 Fixed Files 50 0 0 0 0 Fixed Files 11 0 0 0 4 Broken Files 1 0 0 0 4 Attempt Files 1 0 0 1 1 Follow-up File 7 1 0 1 21 Attempting Files 2 0 0 0 0 Fixed Files 16 0 0 0 0
我希望它返回:

Status Of Matters Delivered Duplicate Error: Invalid Sent Undelivered Broken Files 50 10 0 0 20 Follow-up File 10 2 0 1 15 Fixed Files 12 0 0 0 15 Attempt Files 20 0 0 0 8

1 个答案:

答案 0 :(得分:0)

我认为这应该有效:

Select  ti.Status [Status]
      , SUM(CASE WHEN ls.STID = 7 THEN 1 ELSE 0 END) [Delivered]
      , SUM(CASE WHEN ls.STID = 6 THEN 1 ELSE 0 END) [Duplicate]
      , SUM(CASE WHEN ls.STID = 10 THEN 1 ELSE 0 END) [Error: Invalid]
      , SUM(CASE WHEN ls.STID = 2 THEN 1 ELSE 0 END) [Sent]
      , SUM(CASE WHEN ls.STID = 9 THEN 1 ELSE 0 END) [Undelivered]
From Local LO With(Nolock)
Inner Join Local_Sent ls With(Nolock)
    On LO.ID = ls.localID
Inner Join ls.StatusID SS
    ON ls.StatusID = SS.ID
Inner Join FileStatus FS
    On M.FileStatus = FS.ID
Where Convert(varchar,ls.LoDate,23) = DateAdd(day,-1, Convert(Varchar,GETDATE(),23)
GROUP BY ti.Status