Why an I getting Invalid Column Name in Pivot Table - sql

I am making a Pivot Table in SQL. I am trying to get IsNull(ItemQty, 0) to work. The way I have the code below won't work as it throws the following error. If I change the top Select statement to just Select * from () it'll work. But, that doesn't allow me to do the IsNull then.
The ShipWeekMod and ItemQty are results of CASE statements in the vtc_ItemForecastSummary view. Any thoughts?
Msg 207, Level 16, State 1, Line 16 Invalid column name 'ShipWeekMod'.
Msg 207, Level 16, State 1, Line 16 Invalid column name 'ItemQty'.
select
OfferTypeShipYear, EDPNO, OfferType, ShipYear, ShipWeekMod, IsNull(ItemQty, 0) as ItemQty
from
(
select OfferTypeShipYear, EDPNO, OfferType, ShipYear, ShipWeekMod, ItemQty as ItemQty from vtc_ItemForecastSummary
) DataTable
PIVOT
(
SUM(ItemQty)
FOR ShipWeekMod
IN (
[2],[4],[6],[8],[10],[12],[14],[16],[18],[20],[22],[24], [26],[28],[30],[32],[34],[36],[38],[40],[42],[44],[46],[48],[50],[52]
)
) PivotTable

You can't reuse the column that you pivot on in the select. Instead you have to apply the isnull function to each column returned by the pivot. As this can be tedious to do you might consider rewriting the query to use dynamic sql instead.
It should probably look like this:
select
OfferTypeShipYear, EDPNO, OfferType, ShipYear,
isnull([2],0) as [2],
isnull([4],0) as [4],
isnull([6],0) as [6],
isnull([8],0) as [8]
... etcetera
from (
select
OfferTypeShipYear, EDPNO, OfferType,
ShipYear, ShipWeekMod, ItemQty
from vtc_ItemForecastSummary
) DataTable
PIVOT (
SUM(ItemQty)
FOR ShipWeekMod
IN (
[2],[4],[6],[8],[10],[12],[14],[16],[18],[20],[22],[24],
[26],[28],[30],[32],[34],[36],[38],[40],[42],[44],[46],[48],[50],[52]
)
) PivotTable

Related

How to resolve datatype length difference errors while using unpivot in SQL Server?

I am running below SQL statements in SQL Server which is causing issues due to difference in length of the column types (name=nvarchar(100), address=nvarchar(250)).
select distinct
Id, Label, [Value]
from
(select distinct
coalesce([Value], 'unknown') as Id,
coalesce([Value], 'unknown') + ':' + I as label,
coalesce([Value], 'unknown') as [Value]
from
[dummyDB].[test].[test]
unpivot
([Value] for I in (name, address)) as dataTable
) as t
Error:
Msg 8167, Level 16, State 1, Line 7
The type of column "address" conflicts with the type of other columns specified in the UNPIVOT list.
How to get this resolved?
If you use APPLY and VALUES to unpivot the data instead, you don't get this error. Using these tools is more versatile that the UNPIVOT operator anyway, so I personally prefer them:
SELECT T.ID,
V.Label,
V.[Value]
FROM dbo.Test T
CROSS APPLY (VALUES('Name',T.Name),
('Address',T.Address))V(Label,Value);
If you have non string-type columns, you'll need to explicitly convert them (possibly with a style code):
SELECT T.ID,
V.Label,
V.[Value]
FROM dbo.Test T
CROSS APPLY (VALUES('Name',T.Name),
('Address',T.Address),
('SomeDate',CONVERT(nvarchar(10),T.SomeDate,112)),
('SomeInt',CONVERT(nvarchar(5),T.SomeInt)))V(Label,Value);

Directly referring to Pivot column to allow ISNULL

How do you go about referring to a pivoted column name so that you can include ISNULL around it? In my example below I get the following error:
Msg 207, Level 16, State 1, Line 3
Invalid column name '1234'.
The query:
SELECT *
FROM
(SELECT
ISNULL([1234], 0) as test1,
*
FROM
[Report]('2019-01-01', '2020-01-01')) a
PIVOT
(SUM(amount)
FOR account IN ([1234])
) p
In your sub-query a ISNULL([1234], 0) as test1, you have alias the name to test1
So in the pivot query, you should use the alias name test1 and not [1234]
SELECT *
FROM (
SELECT
ISNULL([1234], 0) as test1,
*
FROM [Report]('2019-01-01', '2020-01-01')
) a
PIVOT (
SUM(amount)
FOR account IN ([test1]) -- change to `test1` here
) p

SELECT query using group by

I don't know why the following query is not working:
SELECT whs_code, pdt_code,case_dt_yyyymmdd, fresh_frozen_status,
SUM(qty_cases_on_hand)-Qty, SUM(qty_weight_on_hand)-Wt, operation
FROM
(
SELECT whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation,SUM(qty_cases_on_hand) AS Qty, SUM(qty_weight_on_hand) AS Wt
FROM tbl_inventory_activity_rpt1
WHERE operation ='RU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation
)
WHERE operation='SU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation`
The error is :
Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'WHERE'.
To make it simple to understand what i am trying to do here, please see the example
I need data as result of
(SELECT x FROM tbl_table Where column y='SU')-(SELECT x FROM tbl_table Where column y='RU')
SELECT ru.whs_code,
ru.pdt_code,
ru.case_dt_yyyymmdd,
ru.fresh_frozen_status,
ru.operation,
ru.Qty - su.Qty AS Qty_Diff,
ru.Wt - su.Wt AS Wt_Diff
FROM
(
SELECT whs_code,
pdt_code,
case_dt_yyyymmdd,
fresh_frozen_status,
operation,
SUM(qty_cases_on_hand) AS Qty,
SUM(qty_weight_on_hand) AS Wt
FROM tbl_inventory_activity_rpt1
WHERE operation ='RU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation
) ru,
(
SELECT whs_code,
pdt_code,
case_dt_yyyymmdd,
fresh_frozen_status,
operation,
SUM(qty_cases_on_hand) AS Qty,
SUM(qty_weight_on_hand) AS Wt
FROM tbl_inventory_activity_rpt1
WHERE operation ='SU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation
) su
WHERE ru.whs_code = su.whs_code
AND ru.pdt_code = su.pdt_code
AND ru.case_dt_yyyymmdd = su.case_dt_yyyymmdd
AND ru.fresh_frozen_status = su.fresh_frozen_status
AND ru.operation = su.operation;

SQL Select with a function

I have the following SQL Statement :
SELECT
RTRIM(LTRIM(REPLACE(LAGKART.VARENUMMER,CHAR(2),''))) AS ItemNo,
RTRIM(LTRIM(REPLACE(LAGKART.SXSON,CHAR(2),''))) AS Season,
ISNULL(RTRIM(LTRIM(REPLACE(LAGKART.VARIANT1,CHAR(2),''))),'') AS Variant1,
ISNULL(RTRIM(LTRIM(REPLACE(LAGKART.VARIANT2,CHAR(2),''))),'') AS Variant2,
(SELECT *
FROM [dbo].[B2BGetSpringFinal] ( LAGKART.VARENUMMER,
LAGKART.VARIANT1,
LAGKART.VARIANT2
)) AS SpringAvailable
FROM
LAGKART
But I get this error :
Msg 170, Level 15, State 1, Line 8
Incorrect syntax near '.'.
But if I call the function with fixed values :
SELECT
RTRIM(LTRIM(REPLACE(LAGKART.VARENUMMER,CHAR(2),''))) AS ItemNo,
RTRIM(LTRIM(REPLACE(LAGKART.SXSON,CHAR(2),''))) AS Season,
ISNULL(RTRIM(LTRIM(REPLACE(LAGKART.VARIANT1,CHAR(2),''))),'') AS Variant1,
ISNULL(RTRIM(LTRIM(REPLACE(LAGKART.VARIANT2,CHAR(2),''))),'') AS Variant2,
(SELECT *
FROM [dbo].[B2BGetSpringFinal] ( '6261',
'Black',
'S'
)) AS SpringAvailable
FROM
LAGKART
I get the desired result.
Any ideas?
Br
Mads
In SQL Server 2000, Only constants and #local_variables can be passed to table-valued functions. In SQL 2005 and greater this was fixed. You could try using a scalar function to get the SpringAvailable column value instead, or look at upgrading to a newer SQL Server version.
if your server supports CTEs you could try this one:
WITH a as (
SELECT VARENUMMER,
RTRIM(LTRIM(REPLACE(LAGKART.VARENUMMER,CHAR(2),''))) AS ItemNo,
RTRIM(LTRIM(REPLACE(LAGKART.SXSON,CHAR(2),''))) AS Season,
ISNULL(RTRIM(LTRIM(REPLACE(LAGKART.VARIANT1,CHAR(2),''))),'') AS Variant1,
ISNULL(RTRIM(LTRIM(REPLACE(LAGKART.VARIANT2,CHAR(2),''))),'') AS Variant2,
FROM LAGKART
)
select *,
(SELECT * FROM [dbo].[B2BGetSpringFinal] ( a.VARENUMMER,
a.VARIANT1,
a.VARIANT2
)) AS SpringAvailable
from a ;
You can use APPLY (CROSS or OUTER) to pass column(s) value(s) as arguments to a function:
SELECT RTRIM(LTRIM(REPLACE(LAGKART.VARENUMMER,CHAR(2),''))) AS ItemNo,
RTRIM(LTRIM(REPLACE(LAGKART.SXSON,CHAR(2),''))) AS Season,
ISNULL(RTRIM(LTRIM(REPLACE(LAGKART.VARIANT1,CHAR(2),''))),'') AS Variant1,
ISNULL(RTRIM(LTRIM(REPLACE(LAGKART.VARIANT2,CHAR(2),''))),'') AS Variant2,
SpringAvailable.*
FROM LAGKART
CROSS APPLY
(
SELECT *
FROM [dbo].[B2BGetSpringFinal] ( LAGKART.VARENUMMER, LAGKART.VARIANT1,LAGKART.VARIANT2 )
) AS SpringAvailable

sql server pivot syntax

I need to do row column transpose and tried a following query
select txn_date,
case when remarks is NULL then 'bank' else remarks end as remarks
from nibl
PIVOT
(
count(txn_date)
FOR remarks IN (bank, remit)
) as pivot
the query above is giving syntax error as below
Msg 156, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'pivot'.
pivot is a reserved word in SQL Server so it is ) as pivot that fails here.
Use another alias ) as p.
did u try it in this way...
select * from
(select txn_date,
case when remarks is NULL then 'bank' else remarks end as remarks
from nibl
) srs
PIVOT
(
count(txn_date)
FOR remarks IN (bank, remit)
) as pivot