![](/img/trans.png)
[英]What do I need to change in my T-SQL pivot query to achieve this specific output?
[英]How can I pivot my T-SQL query output to get this specific table?
我正在SQL Server 2014
上運行T-SQL
查詢。 查詢及其輸出如下:
Use MyDatabase
SELECT
ID,
ArrivalMonth,
DateOfBirth
FROM [View1]
WHERE [ArrivalMonth] between '2017-01-01' and '2018-05-01'
上面查詢的輸出看起來像這樣(摘錄):
ID ArrivalMonth DateOfBirth
101 2017-01-01 1974-05-30
105 2017-05-01 1967-03-05
125 2017-05-01 NULL
... ... ...
我需要一個T-SQL
查詢以提供以下輸出(基於上面的輸出):
ArrivalMonth Number_Of_Bookings Number_Of_DOB_Captured
2017-01-01 130 110
2017-02-01 90 85
... ... ...
2018-05-01 115 70
第一列是ArrivalMonth
。 Number_Of_Bookings
是以上查詢中的記錄數計數。 Number_Of_DOB_Captured
是計數DateOfBirth
是NOT NULL
。
我認為可能是Pivot
查詢可能是解決方案,但對於在這種情況下如何執行它感到困惑。
您可以將包含所有月份的日歷表加入當前表,然后進行匯總:
WITH months AS (
SELECT '2017-01-01' AS month UNION ALL
SELECT '2017-02-01' UNION ALL
...
SELECT '2017-12-01'
)
SELECT
m.month,
COUNT(*) AS Number_Of_Bookings,
COUNT(v.DateOfBirth) AS Number_Of_DOB_Captured
FROM months m
LEFT JOIN [View1] v
ON m.month = v.ArrivalMonth
WHERE
v.ArrivalMonth BETWEEN '2017-01-01' AND '2018-05-01'
GROUP BY
m.month;
如果由於某種原因,給定的到達月份在您的視圖中沒有與之相關聯的數據,則在這里可能需要日歷表。 如果確定該視圖將始終包含每個月的數據,則可以直接在表上進行聚合而無需加入。
您可以使用count(Number_Of_Bookings)
, count(DateOfBirth)
並按group by ArrivalMonth
因此,您需要為每個不同的ArrivalMonth
計算非空值的數量。
查詢:
Select ArrivalMonth
, count(Number_Of_Bookings)
, count(DateOfBirth)
FROM [View1]
WHERE [ArrivalMonth] between '2017-01-01' and '2018-05-01'
group by ArrivalMonth
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.