ISNULL Syntax Challenge - sql

I can't seem to figure out the syntax issue here.
This works, but returns nulls;
SELECT jo.Job_Operation, jo.Job, jo.Work_Center, jo.Operation_Service, jo.Est_Total_Hrs,
(SELECT SUM(jot.Act_Run_Hrs)
FROM PRODUCTION.dbo.Job_Operation_Time jot
WHERE jot.Job_Operation = jo.Job_Operation) AS Cost
FROM PRODUCTION.dbo.Job_Operation jo
WHERE jo.Job = 'A5076027'
So I'm trying to use ISNULL here but I get an error:
SELECT jo.Job_Operation, jo.Job, jo.Work_Center, jo.Operation_Service, jo.Est_Total_Hrs,
(ISNULL(SELECT SUM(jot.Act_Run_Hrs)
FROM PRODUCTION.dbo.Job_Operation_Time jot
WHERE jot.Job_Operation = jo.Job_Operation,0)) AS Cost
FROM PRODUCTION.dbo.Job_Operation jo
WHERE jo.Job = 'A5076027'
The error is:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ','.
Can anyone see what I'm missing here?
Thanks!

try this:
SELECT jo.Job_Operation, jo.Job, jo.Work_Center, jo.Operation_Service, jo.Est_Total_Hrs,
ISNULL((SELECT SUM(jot.Act_Run_Hrs)
FROM PRODUCTION.dbo.Job_Operation_Time jot
WHERE jot.Job_Operation = jo.Job_Operation),0) AS Cost
FROM PRODUCTION.dbo.Job_Operation jo
WHERE jo.Job = 'A5076027'

I don't think you need a correlated subquery here. This seems to me like a standard left join is all that is required.
SELECT jo.Job_Operation
, jo.Job
, jo.Work_Center
, jo.Operation_Service
, jo.Est_Total_Hrs
, SUM(isnull(jot.Act_Run_Hrs, 0)) AS Cost
FROM PRODUCTION.dbo.Job_Operation jo
left join PRODUCTION.dbo.Job_Operation_Time jot ON jot.Job_Operation = jo.Job_Operation
WHERE jo.Job = 'A5076027'
GROUP BY
jo.Job_Operation
, jo.Job
, jo.Work_Center
, jo.Operation_Service
, jo.Est_Total_Hrs

This is far more legible in my opinion
SELECT
jo.Job_Operation, jo.Job, jo.Work_Center, jo.Operation_Service, jo.Est_Total_Hrs
,ISNULL(jot.[SumAct_Run_Hrs],0) AS Cost
FROM PRODUCTION.dbo.Job_Operation jo
LEFT JOIN (
SELECT Job_Operation,SUM(Act_Run_Hrs) [SumAct_Run_Hrs]
FROM PRODUCTION.dbo.Job_Operation_Time
GROUP BY Job_Operation
) jot ON jot.Job_Operation = jo.Job_Operation
WHERE jo.Job = 'A5076027'

Related

Syntax error in Common Table Expression 1

I am trying to create a common table expression but I got an error.
Could you please help me with that.
WITH cte_sales AS(
SELECT
Payments.BankTransaction_Id,
Payments.Paid * InvoiceLines.TotalPrice / Invoices.TotalPayable AS PaymentAmount,
FORMAT( Cast(Payments.Paid / Invoices.TotalPayable as Decimal(6,1)) ,'P0') AS PaymentAmount,
Invoices.TotalPayable,
Payments.PaymentDate,
BankTransactions.TransactionDate,
ProductContracts.Product_Id,
ProductBases.Name AS ProductName,
ProductOptionBases.Name As ProductOptionName,
InvoiceLines.InvoiceLineId,
CubeOrder.Id AS ContractId,
ProductContracts.RowID AS ProductContractId
FROM Payments
INNER JOIN Invoices ON Invoices.Id = Payments.Invoice_Id
INNER JOIN InvoiceLines ON InvoiceLines.Invoice_Id = Invoices.Id
INNER JOIN ProductContracts ON CAST(ProductContracts.ContractID AS VARCHAR(100)) = SUBSTRING(InvoiceLines.InvoiceLineId, 1, 36)
INNER JOIN ProductOptionBases ON CAST(ProductOptionBases.Id AS VARCHAR(5)) = SUBSTRING(InvoiceLines.InvoiceLineId, 38, IIF (CHARINDEX(':', InvoiceLines.InvoiceLineId, 38) = 0, 999, CHARINDEX(':', InvoiceLines.InvoiceLineId, 38))- 38)
INNER JOIN ProductBases ON ProductContracts.Product_Id = ProductBases.Id
INNER JOIN CubeOrder ON CubeOrder.ContractID = Invoices.SubjectID
INNER JOIN BankTransactions ON BankTransactions.Id = Payments.BankTransaction_Id
WHERE ProductContracts.Discriminator = 'RecurringProductContract'
AND Invoices.TotalPayable <> 0
)
The error message is: Msg 102, Level 15, State 1, Line 26 Incorrect syntax near ')'.
You are missing the main query, that you need to add at the end.
For example, a query with a CTE should take the form:
with cte_sales as (
...
)
select * from cte_sales
You are missing that last line.

Feature Summary using Rollup-

I am trying to modify a rollup query I found to use a select statement instead of a view. the rollup is:
select case when (grouping(lut_XXX_type_name) = 1) then 'ALL'
else ISNULL(lut_XXX_type_name, 'unknown')
end as lut_XXX_type_name,
case when (GROUPING(lut_YYY_status_name) = 1)then 'ALL'
ELSE ISNULL(lut_YYY_status_name, 'UNKNOWN')
end as lut_YYY_status_name,
SUM (ZZZ_quantity) as qtySum
from database.dbo.View_permitted
group by lut_XXX_type_name,lut_YYY_status_name with rollup
I want to replace the 'from database.dbo.View_permitted' with the following so I put it in Parenthesis:
SELECT dbo.WWW.WWW_id, dbo.WWW.WWW_grantee, dbo.YYY_entity.YYY_entity_apn, dbo.lut_YYY_status.lut_YYY_status_name,
dbo.lut_entity_type.lut_entity_type_name, dbo.lut_XXX_type.lut_XXX_type_name, dbo.county.county_name, dbo.ZZZ.ZZZ_quantity,
dbo.YYY.YYY_city, dbo.YYY.YYY_term, dbo.YYY.YYY_date_executed
FROM dbo.WWW INNER JOIN
dbo.YYY ON dbo.WWW.WWW_id = dbo.YYY.YYY_WWW_id INNER JOIN
dbo.lut_YYY_status ON dbo.YYY.YYY_lut_YYY_status_id = dbo.lut_YYY_status.lut_YYY_status_id INNER JOIN
dbo.ZZZ ON dbo.WWW.WWW_id = dbo.ZZZ.ZZZ_WWW_id INNER JOIN
dbo.lut_XXX_type ON dbo.ZZZ.ZZZ_lut_XXX_type_id = dbo.lut_XXX_type.lut_XXX_type_id INNER JOIN
dbo.YYY_entity ON dbo.YYY.YYY_id = dbo.YYY_entity.YYY_entity_YYY_id INNER JOIN
dbo.lut_entity_type ON dbo.YYY_entity.YYY_entity_lut_entity_type_id = dbo.lut_entity_type.lut_entity_type_id INNER JOIN
dbo.county ON dbo.WWW.WWW_county_id = dbo.county.county_id
WHERE (dbo.ZZZ.ZZZ_lut_XXX_type_id IN (20, 21, 22, 23, 24, 65, 66)) AND (dbo.county.county_name IN ('County1', 'county2')) AND
(dbo.YYY_entity.YYY_entity_WWW <> 0) AND (dbo.lut_YYY_status.lut_YYY_status_name IN ('Active', 'permitted’))
when I execute, I get the following error:
Msg 156, Level 15, State 1, Line 22
Incorrect syntax near the keyword 'group'.
Msg 319, Level 15, State 1, Line 22
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
I have read threads regarding use of semicolon, I modified the end to be:
group by rollup(lut_XXX_type_name,lut_YYY_status_name)
but it is still not working...
Thanks for your help-
Try this:
group by rollup(lut_XXXXX_type_name, lut_YYYYY_status_name)
with rollup is used in some other databases.

why sql case condition gives error

I do something like this which works fine :
select nameOfCols
from
FACost
inner join FAT as D on d.nid=a.atypeid
and
d.nid in (select item from SplitString('1,2,3,',','))
But when i use case to handle a situation where user dynamically may enter '' instead of '1,2,3,'. Then it gives error in my case condition
declare #selectedAssetTypeID varchar(50)='1,2,3,'
select nameOfCols
from
FACost
inner join FAT as D on d.nid=a.atypeid
and
case when #selectedAssetTypeID<>'' then d.nid in (select item from SplitString( #selectedAssetTypeID,',')) else d.nid=1 end //error causing lines
errors are:
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'in'.
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'else'.
Use and and or conditions instead of a case expression. The case expression as you have it is assigning a value (else d.nid=1) or checking for a true/false condition (d.nid in (select item from SplitString( #selectedAssetTypeID,','))).
and (
(#selectedAssetTypeID <>'' and d.nid in (select item from SplitString( #selectedAssetTypeID,',')) )
or (d.nid=1)
)
you cannot use in clause with case statement. because Case has to return one value per statement (either true or false)
either you can split your queries in two blocks or you can use "OR" clause.
IF #selectedAssetTypeID = " "
BEGIN
select nameOfCols
from FACost
inner join FAT as D
on (d.nid = a.atypeid)
where d.nid = 1
END
ELSE
BEGIN
select nameOfCols
from FACost
inner join FAT as D
on (d.nid = a.atypeid)
where d.nid IN
(select item from SplitString( #selectedAssetTypeID,','))
END
You can also use "OR" clause
select nameOfCols
from FACost
inner join FAT as D
on (d.nid = a.atypeid)
where ((#selectedAssetTypeID <>'' and d.nid in (select item from SplitString(#selectedAssetTypeID,',')))
or (d.nid=1))
link for the discussion about the similar issue is below
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/bc8a7a0b-1980-4481-a2df-6a5fde38f362/in-clause-in-case-statement?forum=sqlgetstarted

Left Join with Case Statement in Sql Server getting ERROR

SELECT
Camp.ID, Inst.StartDate, Ctype.CampaignType,
'Cert' + REPLACE(Ctype.CampaignType, ' ', '') AS CampaignType
FROM
CertCampaign Camp
LEFT JOIN
(SELECT
CASE WHEN CampaignType = 'CertAccounttoRole' THEN CertUserToAccount) t ON Inst.ID = t.InstanceId
LEFT JOIN
CertAccounttoRole ON Inst.ID = t.InstanceId
LEFT JOIN
CertCampaignType Ctype ON Ctype.ID = Camp.CampaignTypeId
LEFT JOIN
CertInstance Inst ON Inst.CampaignId = Camp.ID
Getting error:
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near ')'.
You need an END in your case stmt, you will also have to name that column:
LEFT JOIN(select case when CampaignType='CertAccounttoRole'
then CertUserToAccount
end as InstanceId )t ON
Inst.ID=t.InstanceId

SQL query: Incorrect syntax near the keyword 'TOP'

SELECT #Tax = SUM(QuoteItem.SalesPrice) * TOP (1) Tax.Amount
FROM Tax INNER JOIN
Job ON Tax.TaxId = Job.TaxId INNER JOIN
Quote ON Job.JobId = Quote.JobId INNER JOIN
QuoteItem INNER JOIN
Room ON QuoteItem.RoomId = Room.RoomId ON Quote.QuoteId = Room.QuoteId
WHERE (Room.QuoteId = #QuoteId) AND (QuoteItem.UnitId = #UnitId)
RETURN #Tax
Result:
Msg 156, Level 15, State 1, Procedure fn_GetQuoteUnitTax, Line 54
Incorrect syntax near the keyword 'TOP'.
Note, that when I omit the TOP(1) it says:
Msg 8120, Level 16, State 1, Procedure fn_GetQuoteUnitTax, Line 54
Column 'Tax.Amount' is invalid in the select list because it is not contained in
either an aggregate function or the GROUP BY clause.
I think you need to do this in two separate queries. The first gets the tax amount:
select #tax = Tax.Amount
from Tax
inner join ...whatever else you need here...
where ...
Note that you can't use the 'top' clause when setting the #tax variable value - you will need to do something in your where clause to select the value you want.
Then get the sales price:
select #sales = sum(QuoteItem.SalesPrice
from ...
where ...
Finally return the result:
return #tax * #sales
According to http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=137110:
SELECT #Tax = SUM(QuoteItem.SalesPrice * Tax.Amount)