Using a earlier made Column - sql

I'm making a stored procedure where I have declared a column with the AS "NameofColumn" method. Now I want to use that value again later in the stored procedure. Is there anyway to do this?
CASE
WHEN ((select top 1 stuksweergeven from componenten where componentid = componentlink.componentid) = 1) and ((select AmountKG from componenten where componentid = componentlink.componentid) <> 0) THEN
Amount * (select AmountKG from componenten where componentid = componentlink.componentid)
ELSE
Amount
END AS Amount
Now later I want to do the following
Amount * 10 AS TotalAmount

Use subquery where you count the "Amount" and then make select to from that subquery . Something like that:
select Amount * 10 AS TotalAmount from ( SELECT CASE
WHEN ((select top 1 stuksweergeven from componenten where componentid = componentlink.componentid) = 1) and ((select AmountKG from componenten where componentid = componentlink.componentid) <> 0) THEN
Amount * (select AmountKG from componenten where componentid = componentlink.componentid)
ELSE
Amount
END AS Amount FROM yourtable )e

Related

Improving a SQL teradata query

I have a table like below and I want 'Y' in front of Ref 345 and 789 in the result-set on basis of count(Ref) = 1 where the amount is less than 0. I am using this query to get the desired output. My question is, is there any other (and more efficient) way to do it in Teradata?
SELECT T.Ref,T.AMOUNT, R.Refund_IND as Refund_IND
FROM Table1 t
LEFT JOIN (select 'Y' as Refund_IND, Ref from Table1 where Ref in
(select Ref from Table1 where amount < 0)
group by Ref having count(Ref) = 1) R on t.Ref = R.Ref
You can use window functions to test these conditions:
SELECT
Ref,
Amount,
CASE WHEN COUNT(*) OVER (PARTITION BY REF) = 1 AND Amount < 0 THEN 'Y' ELSE '' END AS Refund_Ind
FROM Table1

Sql server aggregate function and GROUP BY Clause error

I have a query below where it compares the number of stagingCabincrew and StagingCockpitCrew columns from the staging schema and compares them to their data schema equivalent 'DataCabinCrew' and 'DataCockpitCrew'.
Below is the query and the results outputted:
WITH CTE AS
(SELECT cd.*,
c.*,
DataFlight,
l.ScheduledDepartureDate,
l.ScheduledDepartureAirport
FROM
(SELECT *,
ROW_NUMBER() OVER(PARTITION BY LegKey
ORDER BY UpdateID DESC) AS RowNumber
FROM Data.Crew) c
INNER JOIN Data.CrewDetail cd ON c.UpdateID = cd.CrewUpdateID
AND cd.IsPassive = 1
AND RowNumber = 1
INNER JOIN
(SELECT *,
Carrier + CAST(FlightNumber AS VARCHAR) + Suffix AS DataFlight
FROM Data.Leg) l ON c.LegKey = l.LegKey )
SELECT StagingFlight,
sac.DepartureDate,
sac.DepartureAirport,
cte.DataFlight,
cte.ScheduledDepartureDate,
cte.ScheduledDepartureAirport,
SUM(CASE
WHEN sac.CREWTYPE = 'F' THEN 1
ELSE 0
END) AS StagingCabinCrew,
SUM(CASE
WHEN sac.CREWTYPE = 'C' THEN 1
ELSE 0
END) AS StagingCockpitCrew,
SUM(CASE
WHEN cte.CrewType = 'F' THEN 1
ELSE 0
END) AS DataCabinCrew,
SUM(CASE
WHEN cte.CrewType = 'C' THEN 1
ELSE 0
END) AS DataCockpitCrew
FROM
(SELECT *,
Airline + CAST(FlightNumber AS VARCHAR) + Suffix AS StagingFlight,
ROW_NUMBER() OVER(PARTITION BY Airline + CAST(FlightNumber AS VARCHAR) + Suffix
ORDER BY UpdateId DESC) AS StageRowNumber
FROM Staging.SabreAssignedCrew) sac
LEFT JOIN CTE cte ON StagingFlight = DataFlight
AND sac.DepartureDate = cte.ScheduledDepartureDate
AND sac.DepartureAirport = cte.ScheduledDepartureAirport
AND sac.CREWTYPE = cte.CrewType
WHERE MONTH(sac.DepartureDate) + YEAR(sac.DepartureDate) = MONTH(GETDATE()) + YEAR(GETDATE())
AND StageRowNumber = 1 --AND cte.ScheduledDepartureDate IS NOT NULL
--AND cte.ScheduledDepartureAirport IS NOT NULL
GROUP BY StagingFlight,
sac.DepartureDate,
sac.DepartureAirport,
cte.DataFlight,
cte.ScheduledDepartureDate,
cte.ScheduledDepartureAirport
The results are correct, all I need to do is add a condition in the WHERE clause where StagingCabinCrew <> DataCabinCrew AND StagingCockpitCrew <> DataCockpitCrew
If a row appears then we have found an error in the data, I just need helping adding this condition in the WHERE Clause because the columns in the WHERE Clause are referring to a SUM and CASE Function. I just need help manipulating the query so that I can add this WHERE Clause
I will guess you are trying to use an alias in the same query.
You CANT do this, because the alias wont be recognized in the WHERE.
SELECT field1 + field2 as myField
FROM yourTable
WHERE myField > 3
You need to include it in a sub query
with cte2 as (
SELECT field1 + field2 as myField
FROM yourTable
)
SELECT *
FROM cte2
WHERE myField > 3
or repeat the function
SELECT field1 + field2 as myField
FROM yourTable
WHERE field1 + field2 > 3

Select statement to return constant when no records found in table in SQL Server 2008

I am have a table with data and now i need to return zero in select statement if there is no records in table for example. I need to use it in Stored Procedure.
-- If no records exists in below select statement
SELECT ID,Text,Date FROM tblData WHERE ID = 12
IF (##ROWCOUNT = 0)
BEGIN
SELECT -5 AS ID
END
Output:
ID Text Date
ID
-5
Expected output
ID
-5
If you want to return 1 row even when there is no match, you can use aggregation:
SELECT (CASE WHEN COUNT(*) = 0 THEN -5 ELSE MAX(ID) END) as ID
FROM tblData
WHERE ID = 12;
I always use an Exists statment.
if exists(SELECT ID FROM tblData WHERE ID = 12)
select 0 as RowsExist
else
select 1 as RowsExist
For a single scalar value you could use something like;
SELECT ISNULL((SELECT ID FROM tblData WHERE ID = 12), 0) as ID
Rhys
SELECT (CASE WHEN Ta.ID IS NULL THEN TBL.ID
ELSE Ta.ID END) AS ID,Ta.Text,Ta.Date
FROM (VALUES(-5)) AS TBL(ID)
LEFT JOIN
(
SELECT ID,Text,Date FROM tblData WHERE ID = 12
)
AS Ta ON Ta.ID = Ta.ID

Create sql query string

i have a problem to create query for table
mouventDeStock
|| idMv || dateMv ||qteMv || typeMV(bit) || codeMv ||
the feild type is either 0 or 1 if 0 means out of the stock , if 1 means means input of stock
i wanna calculate the qte witch is equal to
qte = ( sum(qteMv) where typeMv = 1 ) - ( sum(qteMv) where typeMv = 0 )
how i can't do it in sql
(select sum(mvQte) from mouvementDeStock
where (mvType = 1 and mvCode = 'ART_18'))
-
(select sum(mvQte) from mouvementDeStock
where (mvType = 0 and mvCode = 'ART_18')
but it's not working at all
Try this...
Select Y.S - X.S As Sum from
(select sum(qteMv) S from mouventDeStock where typemv=1 and codemv = 'ART_18') Y,
(select sum(qteMv) S from mouventDeStock where typemv=0 and codemv = 'ART_18') X;
You can use subqueries to calculate the subtotals, but your entire statement must be a valid SQL statement, so you need to wrap another SELECT around them:
SELECT (SELECT SUM(mvQte) FROM mouvementDeStock
WHERE mvType = 1 AND mvCode = 'ART_18')
-
(SELECT SUM(mvQte) FROM mouvementDeStock
WHERE mvType = 0 AND mvCode = 'ART_18')
If you want to be clever, you can do this with a single sum, by making all out-of-stock mvQte values negative by multiplying them with -1:
SELECT SUM(mvQte * CASE mvType WHEN 0 THEN -1 ELSE 1 END)
FROM mouvementDeStock
WHERE mvCode = 'ART_18'
(CASE expression documentation)

Select statement with a particular logic

I have a table in Microsoft Dynamics AX ERP Database of SQL Server 2008 R2, which has some rows, there is a field named qty in table, some rows have negative qty and some rows have positive quantity. There is another field TransactionID, now I want to select all those TransactionIDs which have negative qty, AND also those TransactionIDs which have some rows with positive QTys and negative qtys too.
TransactionID is a foreign key field of a master table.
So far I wrote below code which is not working.
select * from RBOTRANSACTIONSALESTRANS main where main.qty < 0
and main.DATAAREAID = 'DAT'
and exists
(
select 1 from RBOTRANSACTIONSALESTRANS where QTY > 0
and RBOTRANSACTIONSALESTRANS.DATAAREAID = main.DATAAREAID
and RBOTRANSACTIONSALESTRANS.STORE = main.STORE
and RBOTRANSACTIONSALESTRANS.TERMINALID = main.TERMINALID
)
order by main.TRANSACTIONID
A recap, you want to select all rows for which there exists at least one row with the same TransactionID that has a negative quantity?
select *
from RBOTRANSACTIONSALESTRANS main
where main.DATAAREAID = 'DAT'
and exists
(
select 1
from RBOTRANSACTIONSALESTRANS sub
where sub.QTY < 0
and sub.DATAAREAID = main.DATAAREAID
and sub.STORE = main.STORE
and sub.TERMINALID = main.TERMINALID
and sub.TRANSACTIONID = main.TRANSACTIONID
)
order by main.TRANSACTIONID
The main difference is, that you had a main.QTY < 0 check. And I added sub.TRANSACTIONID = main.TRANSACTIONID.
more or less the query should be like that
select * from
(
select tansactionID, sum(qty) as q, sum(abs(qty)) as q2
from table2 T
group by tansactionID ) T
where q<> q2
post the schema so i can adjust it
JOINed query defines TRANSACTIONID according your conditions (see HAVING conditions). So after JOIN you filter your table to leave only these TRANSACTIONID.
select t.* from RBOTRANSACTIONSALESTRANS t
join
(
select TRANSACTIONID,min(main.qty),max(main.qty)
from RBOTRANSACTIONSALESTRANS main
GROUP BY TRANSACTIONID
HAVING (max(main.qty) < 0)
or
((min(main.qty) < 0) and (max(main.qty) > 0))
) t1 on (t.TRANSACTIONID=t1.TRANSACTIONID)
UPD After you comment under your question I think you need to use only this condition in the inner query:
HAVING not (min(main.qty) < 0)
It seems to me that you may be over complicating the issue. If I am understanding the criteria correctly you want All rows where
the quantity is < 0
OR
the quantity is < 0 AND a row exists with the same transaction ID
with a negative quantity
So to start
SELECT *
FROM RBOTRANSACTIONSALESTRANS tr
WHERE tr.DATAAREAID = 'DAT'
AND tr.Qty < 0
Would satisfy the first criterion. The following would do the second.
SELECT *
FROM RBOTRANSACTIONSALESTRANS tr
WHERE tr.DATAAREAID = 'DAT'
AND tr.Qty > 0
AND EXISTS
( SELECT 1
FROM RBOTRANSACTIONSALESTRANS neg
WHERE neg.TransactionID = tr.TransactionID
AND neg.DATAAREAID = 'DAT'
AND neg.Quantity < 0
)
This can be combined as
SELECT *
FROM RBOTRANSACTIONSALESTRANS tr
WHERE tr.DATAAREAID = 'DAT'
AND ( tr.Qty < 0
OR EXISTS
( SELECT 1
FROM RBOTRANSACTIONSALESTRANS neg
WHERE neg.TransactionID = tr.TransactionID
AND neg.DATAAREAID = 'DAT'
AND neg.Quantity < 0
)
)
However, the first clause is redundant since any row where the quantity is < 0 will also be satisfied by the EXISTS clause. So this can be simplified to:
SELECT *
FROM RBOTRANSACTIONSALESTRANS tr
WHERE tr.DATAAREAID = 'DAT'
AND EXISTS
( SELECT 1
FROM RBOTRANSACTIONSALESTRANS neg
WHERE neg.TransactionID = tr.TransactionID
AND neg.DATAAREAID = 'DAT'
AND neg.Quantity < 0
)