SQL: Not being able to use column alias in where [duplicate] - sql

This question already has answers here:
TSQL - Use a Derived Select Column in the Where Clause
(6 answers)
Closed 1 year ago.
Given the following sql example procedure:
DECLARE #xmlvoucherSequenceList xml = '<?xml version="1.0"?><Voucher><Id Item1="6425"/></Voucher>'
select
col.value('./#Item1','int') voucherSequence
from #xmlvoucherSequenceList.nodes('/Voucher/Id') t(col)
where voucherSequence not in (
...
)
I don't understand why "voucherSequence" alias in where appear underlined in red in the sql management studio editor with "Column voucherSequence not found".
If I comment the where part and run only the select, the voucherSequence clearly appears as the column name (alias).
The weird thing is if I replace the previous query by the next one:
select
col.value('./#Item1','int') voucherSequence
from #xmlvoucherSequenceList.nodes('/Voucher/Id') t(col)
where col.value('./#Item1','int') not in (
...
)
The sql compiler won't complain and the query works fine, but I'd like to use the alias in where, that's why alias is for.

Your code looks like SQL Server. I would recommend:
select v.voucherSequence
from #xmlvoucherSequenceList.nodes('/Voucher/Id') t(col) cross apply
(values (t.col.value('./#Item1', 'int'))
) v(voucherSequence)
where v.voucherSequence not in (
...
)

Related

how to change column into row from grouping sql big query [duplicate]

This question already has answers here:
Unpivot, Split Column, Pivot Bigquery/Postgresql
(2 answers)
Closed 10 days ago.
i have a table SQL similar like this picture:
i want to change the table into something like this, based on their group type.
I'm still have an issue how to change the table, to adding type "attribution / immediate" can somebody suggest me how to do that? Thank you!
Simple variant, to "pivot/unpivot" by auxiliary cte or subquery, applicable if a fixed set of additional columns is specified
with types as( select 'attribution' typeX union all select 'immidate'
)
select device,typeX
,case when b.typeX='attribution' then session_attribution
when b.typeX='immidate' then session_immidate
else null
end session
,case when b.typeX='attribution' then order_attribution
when b.typeX='immidate' then order_immidate
else null
end orderX
from tableA a join types b on 1=1
order by typeX,device
JOIN on condition like 1=1 my be replaced by CROSS APPLY.
Using names similar to reserved words - practice leading to syntactic and semantic errors. In example changer type->typeX, order->orderX.

Reference an alias for an expression in a SELECT statement

I have the following select statement that creates the expression "newdate" and then references in a different expression called "newname":
SELECT
Iif([DateColumn1]='',Format(CONVERT(DATE,Dateadd(day,RIGHT([DateColumn2],3)-1,CONVERT(DATETIME,LEFT([DateColumn2],4)))),'MMddyy'),Format(CONVERT(DATE,Dateadd(day,RIGHT(datecolumn3],3)-1,CONVERT(DATETIME,LEFT([DateColumn3],4)))),'MMddyy')) AS **newdate**,
Upper(LEFT(Rtrim([NameColumn4]),19)+''+[newdate]+''+RIGHT([NameColumn5],3)) AS newname
FROM table1
For some reason when running this I get an error of invalid column and it refers to the "newdate" expression I created. The "newdate" expression works fine but it's when I add the second expression for "newname" that it stops working.
Is there a way to refer to an expression as an alias within another expression that also has an alias?
You can't. But SQL Server has a very nifty feature where you can define the column in the from clause using apply:
SELECT v.newdate,
Upper(LEFT(Rtrim(t1.[NameColumn4]),19) + v.newdate + RIGHT(t1.[NameColumn5], 3)) AS newname
FROM table1 t1 CROSS APPLY
(VALUES ( <complicated expression here)
) v(newdate)
You can't reference an alias within the same scope as its created - you can create it in a sub-query if you wish to avoid repeating the logic.
SELECT
UPPER(LEFT(RTRIM([NameColumn4]),19)+''+[newdate]+''+RIGHT([NameColumn5],3)) AS [NewName]
FROM (
SELECT NameColumn4, NameColumn5
, IIF([DateColumn1]='',FORMAT(CONVERT(DATE,DATEADD(DAY,RIGHT([DateColumn2],3)-1,CONVERT(DATETIME,LEFT([DateColumn2],4)))),'MMddyy'),FORMAT(CONVERT(DATE,DATEADD(DAY,RIGHT(datecolumn3],3)-1,CONVERT(DATETIME,LEFT([DateColumn3],4)))),'MMddyy')) AS NewDate
FROM table1
) X
In SQL Server, there is a concept called ALL AT ONCE, where all operations on a logical query execution phase (SELECT here).So, you are facing issue here.
Detailed Information on All at Once
SELECT FirstName + LastName AS FullName,
Salutation + FullName -- Will throw error here
FROM TableName
You can handle that through multiple ways:
Sub queries Dale K has suggested in another answer
Common Table Expression Given below
;WITH CTE_NewDate AS
(
SELECT
Iif([DateColumn1]='',Format(CONVERT(DATE,Dateadd(day,RIGHT([DateColumn2],3)-1,CONVERT(DATETIME,LEFT([DateColumn2],4)))),'MMddyy'),Format(CONVERT(DATE,Dateadd(day,RIGHT(datecolumn3],3)-1,CONVERT(DATETIME,LEFT([DateColumn3],4)))),'MMddyy')) AS newdate,
NameColumn4, NameColumn5
FROM table1
)
SELECT newDate, Upper(LEFT(Rtrim([NameColumn4]),19)+''+[newdate]+''+RIGHT([NameColumn5],3)) AS newname
FROM CTE_NewDate

MS SQL - group by concat string [duplicate]

This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 6 years ago.
I am new to writing SQL scripts (at least anything more than SELECT * FROM X). I have run into a problem grouping a table by one value, and then joining values from another column into a single string.
I would like to perform a group by on a temp table, and then concatenate values of a column in the group together.
The table variable (edit), #categoriesToAdd, data structure is [SubscriberId int, CategoryId int].
What I am trying to do is something like (My understanding is that CONCAT is the bit missing from MSSQL):
SELECT SubscriberId,
CONCAT(CONVERT(VARCHAR(10), CategoryId) + ', ') as categoriesAdded
FROM #categoriesToAdd
GROUP BY SubscriberId
The concatenated category IDs for each subscriber would then look something like:
0001, 0002, 0003, 0004
Thanks!
In sql server you can use FOR XML PATH
select SubscriberId,
categoriesAdded=Stuff((SELECT ',' + CAST(CategoryId as VARCHAR(255)) FROM catsToAdd t1 WHERE t1.SubscriberId=#categoriesToAdd.SubscriberId
FOR XML PATH (''))
, 1, 1, '' )
from #categoriesToAdd as catsToAdd
GROUP BY SubscriberId

Concatinating Rows Specific Field and Displaying the Concatinated Value in SELECT query-SQL [duplicate]

This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 8 years ago.
My aim is to display the person name and all the reason for his absences(concated and displaying in a string).
I am using the following query to display the EmployeeName, ReasonForAbsence. I am having problem with concatenating and Displaying all record specific column called 'AbsenceReason'. The error is Incorrect Syntax near ='. More info about error- its happening for displaying absence reason part.
SELECT
--Displaying Name,
EMP.NAME,
--Displaying Absence Reason
(
SELECT
#AbsenceReasons= #AbsenceReasons + ';' + REASONTEXT
FROM
ABSENCE
WHERE ID=EMP.ID
)
FROM
(
SELECT
*
FROM
Employees
) EMP
What have I missed?
Thank you
As Martin says this is a duplicated question but...
SELECT DISTINCT Absence.EmpId, Reasons.AllReasons
FROM Absence
CROSS APPLY ( SELECT ReasonText + ' ,'
FROM Absence EMP2
WHERE EMP2.EmpId= Absence.EmpId
FOR XML PATH('')
) Reasons ( AllReasons)

Need help with error in Oracle SQL query

this is the query:
SELECT DISTINCT pprom.pk
FROM
(
SELECT
item_t0.SourcePK as pk
FROM
links item_t0
WHERE (? = item_t0.TargetPK AND item_t0.SourcePK in (?,?))
AND (item_t0.TypePkString=? )
UNION
SELECT
item_t1.TargetPK as pk
FROM
cat2prodrel item_t1
WHERE ( item_t1.SourcePK in (? ) AND item_t1.TargetPK in (?,?))
AND (item_t1.TypePkString=? )
) AS pprom
And this is the error:
ORA-00933: SQL command not properly ended
Any ideas what could be wrong?
Edit:
The question marks are replaced by PKs of the respective items:
values = [PropertyValue:8802745684882, PropertyValue:8796177006593, PropertyValue:8796201713665, 8796110520402, PropertyValue:8796125954190, PropertyValue:8796177006593, PropertyValue:8796201713665, 8796101705810]
Edit 2:
The query is executed deep inside some proprietary software system so I don't know exactly the code that runs it.
Edit 3:
I found one more query that's a little shorter but results in the same error message:
SELECT DISTINCT pprom.pk
FROM
(
SELECT
item_t0.SourcePK as pk
FROM
links item_t0
WHERE (? = item_t0.TargetPK AND item_t0.SourcePK in (?))
AND (item_t0.TypePkString=? )
) AS pprom
Using the following values:
values = [PropertyValue:8799960601490, PropertyValue:8796177006593, 8796110520402]
Edit 4
I found the SQL code that is sent to the db after replacing the values:
SELECT DISTINCT pprom.pk
FROM
(
SELECT
item_t0.SourcePK as pk
FROM
links item_t0
WHERE (8801631769490 = item_t0.TargetPK AND item_t0.SourcePK in (8796177006593))
AND (item_t0.TypePkString=8796110520402 )
) AS pprom
I also tried executing the inner SELECT statement and that alone runs ok and returns a single PK as a result.
I could not find any obvious syntax error in your query so I'd presume the issue is the client library you are using to convert the ? place holders into actual values. Your question edit displays a sort of dump where there are 8 integers but only 6 PropertyValue items. Make sure that's not the issue: IN (?, ?) requires 2 parameters.
Edit
Try removing the AS keyword when you assign an alias to the subquery:
SELECT DISTINCT pprom.pk
FROM
(
SELECT
item_t0.SourcePK as pk
FROM
links item_t0
WHERE (8801631769490 = item_t0.TargetPK AND item_t0.SourcePK in (8796177006593))
AND (item_t0.TypePkString=8796110520402 )
) AS pprom
^^