简体   繁体   English

如何在SQL Server中根据日期范围添加不同的行

[英]How to add different rows based on date range in sql server

I want to add the columns based on different date range and then I want to place the corresponding sum for each date range into a view. 我想基于不同的日期范围添加列,然后将每个日期范围的相应总和放入视图中。

I have a table like below: 我有一个如下表:

Date_From   Available  
01/03/2011       5  
06/03/2011       6  
25/03/2011       7   
14/04/2011       9  
20/04/2011      10  

I want output in a view like this: 我想要在这样的视图中输出:

              Q3        Q4  
Sum           18        19  

where Q3 and Q4 are the total record for month of March and April . 其中Q3和Q4是3月和4月的总记录。

Can somebody tell me what I should do? 有人可以告诉我该怎么做吗?

I'm going to assume that you are not solely concerned with just March and April, and that what you really want is a monthly rollup of totals, each in its own column. 我将假设您不仅只关注3月和4月,而且您真正想要的是每月汇总,每个汇总都在其自己的列中。 Since you are on SQL Server 2005, you can do this with a dynamic PIVOT . 由于您使用的是SQL Server 2005,因此可以使用动态PIVOT进行此操作。 The following code is tested and should return you the totals for each month in a separate column. 以下代码经过测试,应在单独的列中返回每个月的总计。 I added the year as well in case you are running this over multiple years worth of data. 我还添加了年份,以防您运行了多年的大量数据。 You can change the column headings by altering the generated date string, although you must take care to make them unique and to correspondent with the column grouping you want: 您可以通过更改生成的日期字符串来更改列标题,尽管您必须注意使其唯一并与所需的列分组相对应:

CREATE TABLE ##Tab (date_from datetime, available int)
INSERT INTO ##Tab (date_from, available) VALUES ('3/1/2011', 5)
INSERT INTO ##Tab (date_from, available) VALUES('3/6/2011', 6)
INSERT INTO ##Tab (date_from, available) VALUES('3/25/2011', 7)
INSERT INTO ##Tab (date_from, available) VALUES('4/14/2011', 9)
INSERT INTO ##Tab (date_from, available) VALUES('4/20/2011', 10)

DECLARE @month_year varchar(2000)
SELECT  @month_year = STUFF(
   ( SELECT DISTINCT '],[' + CAST(datepart(mm, date_from) AS varchar) + 
         '/' + CAST(datepart(yy, date_from) AS varchar)
     FROM    ##Tab
     ORDER BY '],[' + CAST(datepart(mm, date_from) AS varchar) + 
         '/' + CAST(datepart(yy, date_from) AS varchar)
     FOR XML PATH('')
   ), 1, 2, '') + ']'

DECLARE @dyn_pivot nvarchar(max)

SET @dyn_pivot =
    N'
        SELECT *
        FROM
        (
            SELECT CAST(datepart(mm, date_from) AS varchar) + ''/'' + CAST(datepart(yy, date_from) AS varchar) dt, SUM(available) AS available
            FROM ##Tab
            GROUP BY CAST(datepart(mm, date_from) AS varchar) + ''/'' + CAST(datepart(yy, date_from) AS varchar)
        ) AS SourceTable
        PIVOT
        (
            AVG(available)
            FOR dt IN (' + @month_year + N')
        ) AS PivotTable
    '

EXEC (@dyn_pivot)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM