Using boolean subqueries in SELECT - sql-server

SELECT A.ID AS Asta
,B.GPS.Lat AS Lng
,B.GPS.Long AS Lat
,B.Tipo AS Tipo
,B.Via AS Via
,A.Stato AS Stato
,(
SELECT COUNT(*)
FROM SIBA_Vendite
WHERE Lotto = B.Lotto
AND Data > GETDATE()
) AS Attiva
,(
SELECT TOP (1) Esito
FROM SIBA_Vendite
WHERE Lotto = B.Lotto
ORDER BY Data
) = (
SELECT ID
FROM SIBA_Esiti
WHERE NAME = 'DESERTA'
) AS Deserta
FROM SIBA_Beni B
INNER JOIN SIBA_Aste A ON B.Asta = A.ID
is returning
Messaggio 102, livello 15, stato 1, riga 1
Incorrect syntax near '='.
Messaggio 156, livello 15, stato 1, riga 1
Incorrect syntax near the keyword 'AS'.
The wrong piece is the = between two subqueries. I'm trying to get a boolean result of the = as "Deserta" field

SQL server doesn't have a boolean datatype, so you have no choice but to use a case or an iif expression to handle this case.
e.g.
Deserta =case when (SELECT TOP (1) Esito
FROM SIBA_Vendite
WHERE Lotto = B.Lotto
ORDER BY Data) = (
SELECT ID
FROM SIBA_Esiti
WHERE NAME = 'DESERTA'
) then 1 else 0 end

Related

I'm getting the error "Msg 1033, Level 15, State 1, Line 14 The ORDER BY clause

I'm trying to run the following query and I'm getting this error:
Msg 1033, Level 15, State 1, Line 14
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Here is the query:
WITH cbt_users AS
(
SELECT
mo, eid, rate, cat, quantity AS cbt_hours
FROM
crew.crew_rates
WHERE
rate_type = 'HOMSTUDY_HRS'
),
tot_hrs AS
(
SELECT
mo, eid, rate, quantity AS tot_hrs
FROM
crew.crew_rates
WHERE
rate_type = 'TOT HRS'
),
GU_cbt_compare AS
(
SELECT
cbt_users.mo, cbt_users.eid, cbt_users.rate, cbt_hours, tot_hrs,
CASE WHEN cbt_users.cat = 'REG' THEN 72 ELSE 75 END AS min_GU
FROM
cbt_users
LEFT JOIN
tot_hrs ON cbt_users.mo = tot_hrs.mo AND cbt_users.eid = tot_hrs.eid
ORDER BY
cbt_users.mo, cbt_users.eid
)
SELECT
mo, eid, rate, cbt_hours, tot_hrs, min_GU
FROM
GU_cbt_compare
ORDER BY
mo, eid

Can someone tell me whats wrong in my query? It says Msg 207, Level 16, State 1, Line 1 Invalid column name 'advance'

Select Bills.BillingPeriod, Bills.Description, Amount=iif(payment.AccountNumber is null,Bills.Amount,Bills.Amount-payment.Recieved-payment.advance) From Bills
Left Outer Join (select [AccountNumber],[BillingPeriod],Recieved=sum([Recieved])
from Payment group by [AccountNumber],[BillingPeriod] )
On Payment.AccountNumber = Bills.AccountNumber And Payment.BillingPeriod = Bills.BillingPeriod Where (Payment.AccountNumber is null or Bills.Amount>Payment.Recieved) And Bills.AccountNumber ='002-002' order bybills.BillingPeriod
There is no advance column in your query, try something like this:
select
Bills.BillingPeriod
, Bills.Description
, Amount = iif(pmt.AccountNumber is null
, Bills.Amount
, Bills.Amount - pmt.Recieved - pmt.advance)
from Bills
left join (
select
AccountNumber
, BillingPeriod
, Recieved = sum(Recieved)
, Advance = sum(Advance) /* you didn't have this column */
from Payment
group by
AccountNumber
, BillingPeriod
) pmt /* you should alias the subquery */
on pmt.AccountNumber = Bills.AccountNumber
and pmt.BillingPeriod = Bills.BillingPeriod
where (pmt.AccountNumber is null or Bills.Amount > pmt.Recieved)
and Bills.AccountNumber = '002-002'
order by bills.BillingPeriod

Aliasing in SQL Server

I wrote this query in Oracle and want to compile it as well on SQL Server:
SELECT DISTINCT
HOLDER_CODE, CALCULATED_AMOUNT
FROM
(SELECT
DA.HOLDER_CODE,
ROUND(FAB.AMOUNT * FCE.EXCHANGE_RATE,0) AS CALCULATED_AMOUNT,
FAB.BALANCE_DATE_ID as FAB_DATE,
MAX(FAB.BALANCE_DATE_ID) OVER (PARTITION BY DA.HOLDER_CODE) as MAX_DATE_BALANCE
FROM
DIM_ACCOUNT DA
JOIN
FACT_AS_BALANCE FAB ON FAB.ACCOUNT_ID = DA.ID
JOIN
DIM_AS_CHARACTERISTICS DAC ON DAC.ID = FAB.BALANCE_TYPE_ID
LEFT JOIN
FACT_CURRENCY_EXCHANGE FCE ON FCE.FROM_CURRENCY_ID = FAB.CURRENCY_ID
WHERE
DAC.BALANCE_CLOSING_FLAG = 'Y'
AND TO_CURRENCY_ID = (SELECT DC.ID
FROM DIM_CURRENCY DC
WHERE DC.IS_DEFAULT_CURRENCY = 'Y')
AND FAB.AMOUNT > 0)
WHERE
FAB_DATE = MAX_DATE_BALANCE
ORDER BY
CALCULATED_AMOUNT DESC;
But when I run it I get the following exception:
Error: Incorrect syntax near the keyword 'WHERE'. SQLState: S0001
ErrorCode: 156
So I guess, it's the last where clause, which indicates this. What is wrong and what should it be?
You just need to alias the subquery
SELECT DISTINCT HOLDER_CODE, CALCULATED_AMOUNT
FROM (
SELECT DA.HOLDER_CODE,
//// snip subquery
AND FAB.AMOUNT > 0
) alias_name_here //<--- here
WHERE FAB_DATE = MAX_DATE_BALANCE
ORDER BY CALCULATED_AMOUNT DESC;
You can use as alias_name_here or just alias_name_here - SQL Server allows either syntax.
you must give a name at your "table"
i give is with "as T"
SELECT DISTINCT HOLDER_CODE, CALCULATED_AMOUNT
FROM (
SELECT DA.HOLDER_CODE,
ROUND(FAB.AMOUNT * FCE.EXCHANGE_RATE,0) AS CALCULATED_AMOUNT,
FAB.BALANCE_DATE_ID as FAB_DATE,
MAX(FAB.BALANCE_DATE_ID) OVER (PARTITION BY DA.HOLDER_CODE) as MAX_DATE_BALANCE
FROM DIM_ACCOUNT DA
JOIN FACT_AS_BALANCE FAB ON FAB.ACCOUNT_ID = DA.ID
JOIN DIM_AS_CHARACTERISTICS DAC ON DAC.ID = FAB.BALANCE_TYPE_ID
LEFT JOIN FACT_CURRENCY_EXCHANGE FCE ON FCE.FROM_CURRENCY_ID = FAB.CURRENCY_ID
WHERE DAC.BALANCE_CLOSING_FLAG = 'Y'
AND TO_CURRENCY_ID = (
SELECT DC.ID FROM DIM_CURRENCY DC
WHERE DC.IS_DEFAULT_CURRENCY = 'Y')
AND FAB.AMOUNT > 0
) as T
WHERE FAB_DATE = MAX_DATE_BALANCE
ORDER BY CALCULATED_AMOUNT DESC;

Alias inner join leads to invalid column name

I'm trying to INNER JOIN three tables and get it to return values for XML file, but the values that are from second or third table are returned as
Msg 207, Level 16, State 1, Procedure PROC_Generate_XML_AdForm, Line
18 Invalid column name 'VPrSKzNazev'.
Msg 207, Level 16, State 1, Procedure PROC_Generate_XML_AdForm, Line
20 Invalid column name 'VPrURLCZ1'.
Msg 207, Level 16, State 1, Procedure PROC_Generate_XML_AdForm, Line
22 Invalid column name 'VPrSlevaCZ1'.
Here is the code:
SELECT #xmlVar = (
SELECT t1.IDS AS 'product_id'
,t1.VPrSKzNazev AS 'product_name'
,t1.VPrPodkolekce AS 'product_category_id'
,'http://www.foo.com/' + t1.VPrURLCZ1 AS 'product_deeplink'
,'http://www.foo.com/media-photo/' + t1.IDS + '/370/370.jpg' AS 'product_image'
,CAST(ROUND((100 - t1.ProdejDPH) / 100 * t1.VPrSlevaCZ1, 0) AS INT) AS 'product_price'
FROM SKz AS t1
INNER JOIN VTbProdDalsi
ON t1.IDS = VTbProdDalsi.VPrSKzIDS
INNER JOIN VTbProdDalsi2
ON t1.IDS = VTbProdDalsi2.VPrSKzIDS
WHERE t1.VPrIsMain = 1
AND (
(
SELECT SUM(SKz.StavZ - SKz.ObjedP)
FROM SKz
WHERE IDS = t1.IDS
) > 0
OR (
SELECT SUM(ISNULL(SKz.VPrDodPocet, 0) - SKz.ObjedP)
FROM SKz
WHERE IDS = t1.IDS
) > 0
)
FOR XML PATH('product')
,ROOT('products')
)
I get the idea that it's probably answered somewhere already, but since I'm new to SQL, I'm not sure how to adapt the answers.
I'm on Microsoft SQL Server Management Studio (SQL Server 2008 R2).
Thanks for any replies.
It seems like your problem is residing right here:
,t1.VPrSKzNazev AS 'product_name'
,t1.VPrPodkolekce AS 'product_category_id'
,'http://www.foo.com/' + t1.VPrURLCZ1 AS 'product_deeplink'
I would make sure those names match up with what is in table Skz.
Also, if you can't figure it out, can you give us a list of columns from Skz?
Solved.
The solution was not to use the joined table t1 for variables that were not in the SKz table.
select #xmlVar =
(
select
t1.IDS as 'product_id',
VTbProdDalsi.VPrSKzNazev as 'product_name',
t1.VPrPodkolekce as 'product_category_id',
'http://www.ringit.cz/' + VTbProdDalsi2.VPrURLCZ1 as 'product_deeplink',
'http://www.ringit.cz/media-photo/' + t1.IDS + '/370/370.jpg' as 'product_image',
CAST(ROUND(t1.ProdejDPH - t1.ProdejDPH * VTbProdDalsi.VPrSlevaCZ1/100, 0) AS int) as 'product_price'
from SKz as t1
inner join VTbProdDalsi on t1.IDS = VTbProdDalsi.VPrSKzIDS
inner join VTbProdDalsi2 on t1.IDS = VTbProdDalsi2.VPrSKzIDS
where t1.VPrIsMain = 1 AND t1.VPrGledis = 1 AND
((SELECT SUM(SKz.StavZ - SKz.ObjedP) FROM SKz WHERE IDS = t1.IDS) > 0 OR (SELECT SUM(ISNULL(SKz.VPrDodPocet, 0) - SKz.ObjedP) FROM SKz WHERE IDS = t1.IDS) > 0)
FOR XML PATH ('product'), ROOT ('products')
)

MS SQL: Nested Selects - Mysterious "Invalid column name" error

When I run the following query against a MSSQL 2000
SELECT
DISTINCT(Email),
(SELECT TOP 1 ActivityID
FROM Activity aa, ActivityType tt
WHERE aa.ActivityTypeId = tt.ActivityTypeId
AND aa.ConsumerID = c.ConsumerID
AND tt.ActivityType = 'Something_OptIn') optin,
(SELECT TOP 1 ActivityID
FROM Activity aa, ActivityType tt
WHERE aa.ActivityTypeId = tt.ActivityTypeId
AND aa.ConsumerID = c.ConsumerID
AND tt.ActivityType = 'Something_OptOut') optout
FROM
Activity a,
Consumer c,
ActivityType t
WHERE
c.CountryID = '23'
AND t.ActivityType = 'Something_Create'
AND a.ActivityTypeId = t.ActivityTypeId
AND c.ConsumerID = a.ConsumerID
AND optin > 1
I get the following error
Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 'optin'.
Why does this happen? I can't see why it would be invalid.
SQL Server does not allow you to refer to aliases by name at the same level. To fix this, repeat the column definition:
WHERE
c.CountryID = '23'
AND t.ActivityType = 'Something_Create'
AND a.ActivityTypeId = t.ActivityTypeId
AND c.ConsumerID = a.ConsumerID
AND (SELECT TOP 1 ActivityID
FROM Activity aa, ActivityType tt
WHERE aa.ActivityTypeId = tt.ActivityTypeId
AND aa.ConsumerID = c.ConsumerID
AND tt.ActivityType = 'Something_OptIn'
) > 1
Or use a subquery:
SELECT *
FROM (
SELECT
DISTINCT(Email),
(...) optin,
(...) optout
FROM
Activity a,
Consumer c,
ActivityType t
) as SubqueryAlias
WHERE
c.CountryID = '23'
AND t.ActivityType = 'Something_Create'
AND a.ActivityTypeId = t.ActivityTypeId
AND c.ConsumerID = a.ConsumerID
AND optin > 1
The last line AND optin > 1 is the offender.
The WHERE clause knows nothing about column aliases in the SELECT list.
You should probably subquery this SELECT without the offending condition, and apply that condition to the outer SELECT.
SELECT *
FROM (
SELECT
...
WHERE ... /* everything except 'optin > 1' */
) anyAlias
WHERE optin > 1

Resources