I want to eliminate Null value from the output.
I have already used below technique for my query but still problem is not solved.
SET ANSI_WARNINGS OFF;**
SUM(CASE WHEN [qty] IS NULL THEN 0 ELSE qty END) AS [qty]
Here's my query
SET ANSI_WARNINGS ON;
DECLARE @cols nvarchar(max),
@query nvarchar(max),
@Date DATETIME
SET @Date = DATEADD(mm, -6, CURRENT_TIMESTAMP);
WITH cte AS
(
SELECT 0 AS TheMonth
UNION ALL
SELECT TheMonth + 1
FROM cte
WHERE TheMonth < 5
)
SELECT TheMonth
INTO #temp
FROM cte
SELECT @cols = STUFF((SELECT distinct ',' + QUOTENAME(A.warehouse_name)
from RS_Company_Warehouse_Master a
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET ANSI_WARNINGS OFF;
SELECT @query = 'SELECT
LEFT(DATENAME(MONTH,DATEADD(MONTH,TheMonth -6 + 1,GETDATE())),3) AS [month],
DATEPART(YEAR,DATEADD(MONTH,TheMonth - 6 + 1 ,GETDATE())) AS [year],
'+@cols+'
from
(
SELECT
TheMonth,
SUM(CASE WHEN [qty] IS NULL THEN 0 ELSE qty END) AS [qty],
warehouse_name
FROM
#temp
LEFT OUTER JOIN RS_Sell_Order_Master AS SM ON invoice_date >= DATEADD(MM, TheMonth, '''+convert(varchar(10), @Date, 120)+''')
AND invoice_date < DATEADD(MM, TheMonth + 1, '''+convert(varchar(10), @Date, 120)+''')
LEFT OUTER JOIN RS_Company_Warehouse_Master AS CWM ON CWM.c_warehouse_id = SM.c_warehouse_id
LEFT OUTER JOIN RS_Sells_Invoice_Info_Master AS SIIM ON SIIM.sell_order_no = SM.sell_order_no
GROUP BY
CWM.warehouse_name,
TheMonth
) as a
PIVOT
(
sum(qty) for warehouse_name
IN ('+@cols+')
) AS P
'
execute sp_executesql @query;
DROP TABLE #temp
Output:
1条答案
按热度按时间ilmyapht1#
Create two @cols list. In one Add is null check in the final Pivot columns as:
SQL Fiddle Demo Here