T-sql query between event table and date range

According to the following table

id  Title   Date            Metadata  
------------------------------------
1   A       08/01/2010      M1
1   A       10/05/2010      M2
1   A       03/15/2011      M3
2   B       09/20/2010      M1
2   B       01/15/2011      M2
3   C       12/15/2010      M1

Input variables will be the start and end dates. For example,

@startDate = '07/01/2010' 
@endDate = '06/30/2011'

How to generate output below?

Title  Jul-10  Aug-10 Sep-10 Oct-10 Nov-10  Dec-10 Jan-11 Feb-11 Mar-11 Apr-11 May-11 Jun-11
-------------------------------------------------------------------------------------------
A      Null    M1     Null    M2     Null   Null   Null    Null   M3     Null   Null   Null
B      Null    M1     Null    Null   Null   Null   M2      Null   Null   Null   Null   Null
C      Null    Null   Null    Null   Null   M1     Null    Null   Null   Null   Null   Null
+3
source share
2 answers

What you are looking for is usually called a cross tabular query. If you ask how to build a crosstab query based on a static list of columns, you can do something like this:

Select Title
    , Min( Case When DatePart(mm, [Date]) = 7 And DatePart(yy, [Date]) = 2010 Then MetaData End ) As [Jul-10]
    , Min( Case When DatePart(mm, [Date]) = 8 And DatePart(yy, [Date]) = 2010 Then MetaData End ) As [Aug-10]   
    , Min( Case When DatePart(mm, [Date]) = 9 And DatePart(yy, [Date]) = 2010 Then MetaData End ) As [Sep-10]       
    ...
From Table
Where [Date] Between @StartDate And @EndDate
Group By Title

, PIVOT, Broken Link. , PIVOT . ( - a.k.a.), , T-SQL . SQL, . , -.

+3

Pivot.

.

    USE AdventureWorks;
GO

SELECT DaysToManufacture, AVG(StandardCost) AS AverageCost 
FROM Production.Product
GROUP BY DaysToManufacture; 



DaysToManufacture  AverageCost  
0                  5.0885  
1                  223.88  
2                  359.1082  
4                  949.4105 

    SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days,   
[0], [1], [2], [3], [4]  
FROM  
(SELECT DaysToManufacture, StandardCost   
    FROM Production.Product) AS SourceTable  
PIVOT  
(  
AVG(StandardCost)  
FOR DaysToManufacture IN ([0], [1], [2], [3], [4]) 
) AS PivotTable;  

Cost_Sorted_By_Production_Days   0                     1                     2                     3                     4

AverageCost                    5.0885                223.88                359.1082              NULL                  949.4105
+2

Source: https://habr.com/ru/post/1750717/