3

我对编写 SQL 比较陌生。我有一个要求,我必须按原样显示前 5 条记录,并将其余记录合并为 1 条记录并将其附加为第 6 条记录。我知道前 5 个选择前 5 个记录,但我发现很难组合一个逻辑来合并其余记录并将其附加到结果集的底部。

weekof          sales    year    weekno
-------------------------------------------------------------
07/01 - 07/07   2   2012    26  
07/08 - 07/14   2   2012    27  
07/29 - 08/04   1   2012    30  
08/05 - 08/11   1   2012    31  
08/12 - 08/18   32  2012    32  
08/26 - 09/01   2   2012    34  
09/02 - 09/08   8   2012    35  
09/09 - 09/15   46  2012    36   
09/16 - 09/22   26  2012    37

我希望这显示为

weekof          sales
----------------------
09/16 - 09/22   26  
09/09 - 09/15   46  
09/02 - 09/08   8   
08/26 - 09/01   2   
08/12 - 08/18   32  
07/01 - 08/11   6
4

2 回答 2

14

除非跨越数年,否则这将以正确的顺序weekof获得您想要的数据

;WITH x AS 
(
  SELECT weekof, sales, 
    rn = ROW_NUMBER() OVER (ORDER BY [year] DESC, weekno DESC) 
  FROM dbo.table_name
)
SELECT weekof, sales FROM x WHERE rn <= 5
UNION ALL
SELECT MIN(LEFT(weekof, 5)) + ' - ' + MAX(RIGHT(weekof, 5)), SUM(sales)
FROM x WHERE rn > 5    
ORDER BY weekof DESC;

当返回的行跨越一年时,您可能还必须返回 rn(并在表示层忽略它):

;WITH x AS 
(
  SELECT weekof, sales, 
    rn = ROW_NUMBER() OVER (ORDER BY [year] DESC, weekno DESC) 
  FROM dbo.table_name
)
SELECT weekof, sales, rn FROM x WHERE rn <= 5
UNION ALL
SELECT MIN(LEFT(weekof, 5)) + ' - ' + MAX(RIGHT(weekof, 5)), SUM(sales), rn = 6 
FROM x WHERE rn > 5
ORDER BY rn;
于 2012-09-12T19:35:35.833 回答
0

这是一个替代版本,即使跨年也能以正确的顺序显示,并且需要一次扫描而不是两次(仅当数据量很大时才重要)。它将在 SQL 2005 及更高版本中工作:

WITH Sales AS (
   SELECT
      Seq = Row_Number() OVER (ORDER BY S.yr DESC, S.weekno DESC),
      *
   FROM dbo.SalesByWeek S
)
SELECT
   weekof =
      Substring(Min(Convert(varchar(11), S.yr) + Left(S.weekof, 5)), 5, 5)
      + ' - '
      + Substring(Max(Convert(varchar(11), S.yr) + Right(S.weekof, 5)), 5, 5),
   sales = Sum(S.sales)
FROM
   Sales S
   OUTER APPLY (SELECT S.Seq WHERE S.Seq <= 5) G
GROUP BY G.Seq   
ORDER BY Coalesce(G.Seq, 2147483647)
;

还有一个查询可能对非常大的数据集执行得更好,因为它不计算行号(改为使用 TOP 一次)。但这都是理论上的,没有真实的数据和性能测试:

SELECT
   weekof =
      Substring(Min(Convert(varchar(11), S.yr) + Left(S.weekof, 5)), 5, 5)
      + ' - '
      + Substring(Max(Convert(varchar(11), S.yr) + Right(S.weekof, 5)), 5, 5),
   sales = Sum(S.sales)
FROM
   dbo.SalesByWeek S
   LEFT JOIN (
      SELECT TOP 5 *
      FROM dbo.SalesByWeek
      ORDER BY yr DESC, weekno DESC
   ) G ON S.yr = G.yr AND S.weekno = G.weekno
GROUP BY G.yr, G.weekno
ORDER BY Coalesce(G.yr, 9999), G.weekno
;

最终,我真的不喜欢使用字符串操作来提取日期范围。如果表格将MinDateandMaxDate作为单独的列会更好,然后为它们创建标签会更简单。

于 2013-06-06T01:36:37.207 回答