Directly referring to Pivot column to allow ISNULL - sql

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

Related

Select top n after data operations SQL

I want to
Filter a data set
Take distinct of a column
take out top 10 rows of that data set with the distinct column
The code I am using is
SELECT TOP (10) *
FROM (
SELECT DISTINCT(business_id) FROM businessdata
WHERE businessdata.city = 'Phoenix'
)
;
and the error I am getting is
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near ';'.
Where am I going wrong?
You have to give a name to the subquery:
SELECT TOP (10) *
FROM (
SELECT DISTINCT(business_id) FROM businessdata
WHERE businessdata.city = 'Phoenix'
) AS my_subquery
ORDER BY businessdata
;
make sure you also an ORDER BY to correctly set the order and thus make TOP meaningful

SQL query to replace a string and convert rest of the string to Int

I have the below query. This query is supposed to look into my accounts table with my where parameter. That will return all account codes which start with leading 3 letters "DAG". The data return is consistently in the format leading with three letters followed by a number. I then want to get the most largest number. For that I order the string by converting it to Int.
I get this below error:
Msg 207, Level 16, State 1, Line 24
Invalid column name 'AccountCodeWithoutDAG '.
Here is my SQL query.
SELECT TOP 1
REPLACE(AccountCode, 'DAG', '') AS AccountCodeWithoutDAG
FROM
Accounts
WHERE
MangCode = 'ADFG'
ORDER BY
CONVERT(INT, AccountCodeWithoutDAG)
What am I doing wrong?
You can't use order by with convert alias
but you can try to use a subquery to get the AccountCodeWithoutDAG then order by it
SELECT TOP 1 AccountCodeWithoutDAG
FROM
(
SELECT REPLACE(AccountCode,'DAG','') AS AccountCodeWithoutDAG
FROM Accounts
where MangCode = 'ADFG'
) t1
Order by Convert(int, AccountCodeWithoutDAG )
As others have indicated, giving a calculated value an alias in the select does not give you the ability to use the same alias in subsequent clauses.
The way to do this nice-and-organized in sql server is cross apply:
SELECT TOP 1 AccountCodeWithoutDAG
FROM Accounts
cross apply (select REPLACE(AccountCode,'DAG','') AS AccountCodeWithoutDAG ) as calcquery
where
MangCode = 'ADFG'
Order by Convert(int, AccountCodeWithoutDAG )
The problem is the AccountCodeWithoutDAG, this is an alias and cannot be used in the order
Look what I did in testing below , use your replace statement in the convert part of the order by
declare #AccountCode varchar(100)='DAG123456'
SELECT top 1 REPLACE(#AccountCode,'DAG','') AS AccountCodeWithoutDAG
Order by Convert(int, REPLACE(#AccountCode,'DAG',''))

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;

Why an I getting Invalid Column Name in Pivot Table

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

SQL Server View Incorrect syntax

i have the following DB:
I want to create view that give this information in a row:
document_id Creator Manager Special Archive
(Creator,Manager,Special,Archive) are AuthorityName values
So fisrt i created a view:
SELECT dbo.DocumentAuthorities.DocumentId, dbo.DocumentAuthorities.AuthorityId, dbo.Authorities.AuthorityName, dbo.Authorities.AuthorityLevel
FROM dbo.DocumentAuthorities CROSS JOIN
dbo.Authorities
then i tried this:
SELECT * FROM
(
SELECT Documents.Id, AuthorityName.AuthorityId, AuthorityName.AuthorityName
FROM AuthorityName CROSS JOIN Documents
) src
PIVOT
(
max(dbo.AuthorityName.AuthorityName)
FOR AuthorityName
IN ([Creator],[Director],[Special],[Archive])
)
but i get this error:
Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ')'.
try this:
You have to give an alias name for your pivot table
SELECT * FROM
(
SELECT Documents.Id, AuthorityName.AuthorityId, AuthorityName.AuthorityName
FROM AuthorityName CROSS JOIN Documents
) src
PIVOT
(
max(dbo.AuthorityName.AuthorityName)
FOR AuthorityName
IN ([Creator],[Director],[Special],[Archive])
) P -- < HERE