2013-11-21 223 views
0

我有一個選擇查詢的,Sql Server的聚合函數

SELECT isnull(T1.TotalShows, 0) AS TotalShows, isnull(T1.ScreenCapacity, 0) AS ScreenCapacity, isnull(T1.ShowDate, 0) AS ShowDate, isnull(T2.TotalTicketsSold, 0) AS TotalTicketsSold, isnull(T2.Nett, 0) AS Nett 
FROM (
    SELECT COUNT(showtimeId) AS TotalShows, sum(sc.Capacity) AS ScreenCapacity, ShowDate 
    FROM Shows s 
    JOIN Screens sc ON sc.ScreenID = s.ScreenID 
    WHERE s.MovieID = 34 
     AND s.IsDeleted = 0 
    GROUP BY ShowDate 
    ) AS T1 
LEFT OUTER JOIN (
    SELECT s.ShowDate, COUNT(ut.UserTicketID) AS TotalTicketsSold, SUM(ISNULL((Price + ConvinienceCharge - DiscountAmount)/(EntertainmentTax + BoxOfficeTax + 1), 0)) AS Nett 
    FROM Shows s 
    LEFT OUTER JOIN UserTickets ut ON s.ShowID = ut.ShowID 
    WHERE ut.ShowID IN (
      SELECT ShowID 
      FROM Shows 
      WHERE MovieID = 34 
       AND IsDeleted = 0 
      GROUP BY ShowID 
      ) 
    GROUP BY s.ShowDate 
    ) AS T2 ON T1.ShowDate = T2.ShowDate 

這將返回數據, enter image description here

我要彙總數據,如

SUM(totalShows),SUM(ScreenCapacity),MAX(ShowDate),SUM(TotalTicketsSold),SUM(Nett) 

但我想這只是前面7行,如上圖所示。對於超過7行,我想要下一行中的聚合數據。

回答

1

如何:

GROUP BY DATEPART(YEAR, ShowDate), DATEPART(WEEK, ShowDate) 
+0

真的,它的工作了整整7行。但是,你介意告訴可能是10行或更多行嗎? – Jeetendra

+0

我是在假設你真的想按周分組。這使您可以按星期分組,無論任何給定星期的所有七天是否都在表格中呈現。 (即如果缺少一個日期,它將不會一直移動,直到達到七個,但該特定組將是六個記錄的總和)。這不能被解釋爲任意聚集函數。 –

+0

如果你確實需要一個任意的聚集函數,你可以用'row_number'做一些事情,並且可以用可以被相同的任意數字整除的項目進行分組。 [Demo](http://sqlfiddle.com/#!6/ecec3/17) –