SQL : ISNULL in Join condition - sql

Is there any other way to write this. If the Credit cardID in Application table is NULL, then join CreditcardID from Terminatedcreditcard table. Thanks,
This is the error:
Msg 4104, Level 16, State 1, Line 18
The multi-part identifier "TC.CreditCardID" could not be bound.
Code:
SELECT DISTINCT
prg.Title AS Program, a.Patientid,
a. Applicationid,
PT.MCC,
PT.MerchantName,
PT.MerchantCity, PT.MerchantState,
PT.MerchantZip,
PT.SettlementTransactionID,
CONVERT(DATE, PT.SettlementDate) AS SettlementDate
ABS(PT.Amount) as TransactionAmount
FROM
[dbo].[StagingSettlements] PT
LEFT JOIN
dbo.Application a ON PT.[CustomId] = ISNULL(a.CreditCardId, TC.CreditCardID)
LEFT JOIN
dbo.TerminatedCreditCard TC ON TC.ApplicationId = a.ApplicationId

You can change join precedence to get this:
FROM [dbo].[StagingSettlements] AS PT
LEFT JOIN ( dbo.Application AS a
LEFT JOIN dbo.TerminatedCreditCard AS TC on TC.ApplicationId = a.ApplicationId )
ON PT.[CustomId] = ISNULL( a.CreditCardId, TC.CreditCardID )
The addition of parentheses above causes Application to TerminatedCreditCard join to be evaluated first and the result is then joined to StagingSettlements.

A couple of points:
You don't appear to actually be using a credit card number in your result set, so I'm not clear on why you want it?
You need to put the NULL check in the join on TerminatedCreditCard. You are getting the error because you are trying to reference TerminatedCreditCard before you have joined to it.
The below SQL should sort you out, I wasn't sure of what the join condition would be between StagingSettlements and application, so I have just put in a placeholder which you will need to update, I have also added a 'CreditCardId' to the select:
SELECT Distinct
prg.Title as Program
,a.Patientid
,a.Applicationid
,PT.MCC
,PT.MerchantName
,PT.MerchantCity
,PT.MerchantState
,PT.MerchantZip
,PT.SettlementTransactionID
,convert(Date,PT.SettlementDate) as SettlementDate
,ABS(PT.Amount) as TransactionAmount
,COALESCE(TC.CreditCardId, a.CreditCardId) as CreditCardId
FROM [dbo].[StagingSettlements] PT
LEFT JOIN dbo.Application a
ON a.<applicationid> = PT.<applicationid>
LEFT JOIN dbo.TerminatedCreditCard TC
ON TC.ApplicationId = a.ApplicationId
AND a.CreditCardId IS NULL

Related

An aggregate may not appear in the WHERE clause (MSSM studio)

I am trying to create a trigger for insert on Advertisement table. When trying to write this cursor
declare Users cursor for
Select "User".IDUser, Sum(Price)
from "User"
inner join Purchase as pu on "User".IDUser = pu.IDUser
inner join PurchaseProduct as pp on pu.IDPurchase = pp.IDPurchase
inner join Product as pr on pp.IDProduct = pr.IDProduct
inner join inserted on pr.IDProduct = inserted.IDProduct
where pr.ProductType = (select ProductType
from Product
inner join Advertisement on Product.IDProduct = Advertisement.IDProduct
inner join inserted on Advertisement.IDProduct = inserted.IDProduct
where Advertisement.IDAdvertisement = inserted.IDAdvertisement)
and Sum(Price) > 50;
I get this error
Msg 147, Level 15, State 1, Procedure AutomaticUserAdvertisementScoreCalculating, Line 15 [Batch Start Line 113]
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
What might be the error here? Below you can see my DB structure
Thanks in advance
You could use HAVING to filter rows after aggregation:
declare Users cursor for
Select "User".IDUser, Sum(Price) from "User"
join Purchase as pu on "User".IDUser = pu.IDUser
join PurchaseProduct as pp on pu.IDPurchase = pp.IDPurchase
join Product as pr on pp.IDProduct = pr.IDProduct
join inserted on pr.IDProduct = inserted.IDProduct
where pr.ProductType = (select ProductType from Product
join Advertisement on Product.IDProduct = Advertisement.IDProduct
join inserted on Advertisement.IDProduct = inserted.IDProduct
where Advertisement.IDAdvertisement = inserted.IDAdvertisement)
GROUP BY "User".IDUser
HAVING Sum(Price) > 50;

Oracle (Netsuite) SQL one join limit results

I have an oracle SQL query and a slight problem. I need to check if an item has a PO# that it has at least 1 line item. The query below works however it returns a result for each line of transaction_lines and I need only une result. PS I tried DISTINCT but get an ODBC error.
SELECT ITEMS.NAME, INVENTORY_NUMBER.INVENTORY_NUMBER, INVENTORY_NUMBER.ON_HAND_COUNT, ITEMS.SALESDESCRIPTION, CONDITION.LIST_ITEM_NAME,
BRAND_PARTNER.LIST_ITEM_NAME, PPROGRAM.LIST_ITEM_NAME, ENTITY.NAME, PO.TRANSACTION_NUMBER, INVENTORY_NUMBER.RECEIVED_COST, ITEMS.SALESPRICE, IR.TRANSACTION_NUMBER,
INVENTORY_SOURCE.LIST_ITEM_NAME, LOCATIONS.NAME, INVENTORY_NUMBER.RECEIPT_DATE, PO.INTERNAL_MEMO, INVENTORY_NUMBER.REFERENCE_, TEST_RESULTS.LIST_ITEM_NAME,
INVENTORY_NUMBER.TEST_FILE_LINK, INVENTORY_NUMBER.CONNECT_TRADE_ID, INVENTORY_NUMBER.SOLD_DATE, INVENTORY_NUMBER.SOLD_PRICE, INVENTORY_NUMBER.MEMO, ITEMS.UPC_CODE, ITEMS.MPN,
ITEMS.ITEM_ID, INVENTORY_NUMBER.CLEI, INVENTORY_NUMBER.CERTIFICATION_REF_ID
FROM INVENTORY_NUMBER
INNER JOIN ITEMS ON INVENTORY_NUMBER.ITEM_ID = ITEMS.ITEM_ID
INNER JOIN TRANSACTIONS AS PO ON INVENTORY_NUMBER.PURCHASE_ORDER_ID = PO.TRANSACTION_ID
INNER JOIN TRANSACTIONS AS IR ON INVENTORY_NUMBER.ITEM_RECEIPT_ID = IR.TRANSACTION_ID
INNER JOIN TRANSACTION_LINES ON PO.TRANSACTION_ID = TRANSACTION_LINES.TRANSACTION_ID
INNER JOIN ENTITY ON TRANSACTIONS.ENTITY_ID = ENTITY.ENTITY_ID
INNER JOIN CONDITION ON INVENTORY_NUMBER.CONDITION_ID = CONDITION.LIST_ID
INNER JOIN BRAND_PARTNER ON INVENTORY_NUMBER.BRAND_PARTNER_ID = BRAND_PARTNER.LIST_ID
INNER JOIN PPROGRAM ON INVENTORY_NUMBER.PROGRAM_ID = PPROGRAM.LIST_ID
INNER JOIN INVENTORY_SOURCE ON INVENTORY_NUMBER.INVENTORY_SOURCE_ID = INVENTORY_SOURCE.LIST_ID
INNER JOIN LOCATIONS ON INVENTORY_NUMBER.LOCATION_ID = LOCATIONS.LOCATION_ID
INNER JOIN TEST_RESULTS ON INVENTORY_NUMBER.TEST_RESULTS_ID = TEST_RESULTS.LIST_ID
WHERE INVENTORY_NUMBER.ON_HAND_COUNT IS NOT NULL AND ((INVENTORY_NUMBER.PURCHASE_ORDER_ID IS NULL) OR (INVENTORY_NUMBER.PURCHASE_ORDER_ID IS NOT NULL AND TRANSACTION_LINES.TRANSACTION_LINE_ID IS NOT NULL))
you could also remove the join to the transaction_lines and instead of tl.TRANSACTION_LINE_ID IS NOT NULL use an exists clause
and exists (select 1 from transaction lines tl
where tl.transaction_id = po.transaction_id)
I would suggest using a GROUP BY to help limit your results. You could also if you are interacting with transactions in your query you must always remember that without limiting results based on the "main line" you will receive the header record and then a record for each individual line item.
If you were doing this with a saved search you could put the criteria as "main line = true". Since I don't understand your query entirely I can't advise where to put this limitation in.

select list because it is not contained in either an aggregate function or the GROUP BY clause

My query throws this error on execution - how to solve this?
Msg 8120, Level 16, State 1, Line 1
Column 'master_order.order_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Here is the query
SELECT
master_order.order_id, master_order.order_no,
master_order.program_no, master_order.package_type,
article_production.article_code, article_production.weight,
article_production.gsm, color.color_name, color.color_no,
size.size_name, transaction_order.quantity, transaction_production.avrg,
transaction_production.total_weight, transaction_order.piece_carton,
transaction_order.no_of_carton, transaction_order.unit_name,
transaction_order.packs, transaction_order.kdnr,
master_order.order_date, inlay.inlay_name, yarn.yarn_count,
buyer.buyer_code, master_production.shipment_date,
master_order.confirmation_date, master_order.comments,
master_production.carton_label, carton.carton_size, carton.carton_value,
master_order.special_instruction, master_order.ean_code1,
master_order.ean_code2, master_order.ean_code3, master_order.ean_code4,
article_production.article_name, transaction_order.piece_weight,
article_production.machine_size, article_production.guage,
master_production.image_path, transaction_production.m3,
transaction_order.tabpage_no, transaction_order.serial_sort,
master_order.total_tabpage,
When I add this error shown
sum(distinct transaction_production.m3) as tm3
Continuing with existing code...
from
transaction_order
LEFT JOIN
article_order on transaction_order.article_id = article_order.article_id
LEFT JOIN
size on transaction_order.size_id = size.size_id
LEFT JOIN
color on transaction_order.color_id = color.color_id
INNER JOIN
master_order ON transaction_order.order_id = master_order.order_id
LEFT JOIN
buyer ON master_order.buyer_id = buyer.buyer_id
INNER JOIN
master_production ON master_order.order_id = master_production.order_id
LEFT JOIN
transaction_production ON transaction_order.trans_id = transaction_production.trans_id
LEFT JOIN
article_production on transaction_production.article_id = article_production.article_id
LEFT JOIN
inlay on master_production.inlay_id = inlay.inlay_id
LEFT JOIN
carton ON transaction_production.carton_id = carton.carton_id
LEFT JOIN
yarn ON transaction_production.yarn_id = yarn.yarn_id
WHERE
master_order.program_no = '13-101117'
As soon as you used sum(...), an aggregate function, you need to use a GROUP BY
Furthermore, you have HTML in your SQL code.
...
sum(distinct transaction_production.m3) as tm3 <p>when i add this error shown</p>
...
Is causing your problems

SQL Query is invalid in the select list

I dont know why this is coming up as invalid and I can not figure it out. I was given a legacy database as my supervisor left and I am in charge until someone comes to replace him. I am trying to run this query...
SELECT tblM.guidRId, SUM(dbo.tblCH.curTotalCost) AS curValue
FROM tblCH INNER JOIN
tblM ON tblCH.guidMId = tblM.guidMId INNER JOIN
ViewLM ON tblM.strNumber = ViewLM.strNumber
WHERE (tblM.guidRId = '4d832bc8-1827-4054-9896-6111844b0f26')
The error I keep getting is...Msg 8120, Level 16, State 1, Line 1
Column 'tblM.guidRId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Why is this error occuring?
You are forgetting to group guidRId. (you are aggregating the data)
SELECT
tblM.guidRId,
SUM(dbo.tblCH.curTotalCost) AS curValue
FROM
tblCH
INNER JOIN tblM ON tblCH.guidMId = tblM.guidMId
INNER JOIN ViewLM ON tblM.strNumber = ViewLM.strNumber
WHERE
tblM.guidRId = '4d832bc8-1827-4054-9896-6111844b0f26'
GROUP BY tblM.guidRId
Because you need a GROUP BY if you are going to use an aggregate functon like SUM() [or COUNT, AVG(), etc...] with another non-aggregate column:
SELECT tblM.guidRId, SUM(dbo.tblCH.curTotalCost) AS curValue
FROM tblCH
INNER JOIN tblM
ON tblCH.guidMId = tblM.guidMId
INNER JOIN ViewLM
ON tblM.strNumber = ViewLM.strNumber
WHERE tblM.guidRId = '4d832bc8-1827-4054-9896-6111844b0f26'
GROUP BY tblM.guidRId;
Try:
SELECT
tblM.guidRId, SUM(dbo.tblCH.curTotalCost) AS curValue
FROM
tblCH
INNER JOIN tblM
ON tblCH.guidMId = tblM.guidMId
INNER JOIN ViewLM
ON tblM.strNumber = ViewLM.strNumber
WHERE (tblM.guidRId = '4d832bc8-1827-4054-9896-6111844b0f26')
GROUP BY tblM.guidRId

Advanced SQL INSERT

I have this query that works fine. It selects rows into the SY.UserOptions table for the ‘Jeff’ user.
However, I created another query that I want to do the same thing, but for every user. So I added SY.Users to the query, which in effect mulplies the 2 tables together. However, it gives me an error that I do not understand.
--This works
SELECT ‘Jeff’, t.Application, t.Task, tl.Description
FROM SY.Tasks t
LEFT OUTER JOIN SY.TaskLevels tl
ON t.Application = tl.Application And t.Task = tl.Task AND t.DftAccessLevel = tl.AccessLevel
-- This does not work
SELECT u.[User], t.Application, t.Task, tl.Description
FROM SY.Tasks t, SY.Users u
LEFT OUTER JOIN SY.TaskLevels tl
ON t.Application = tl.Application And t.Task = tl.Task AND t.DftAccessLevel = tl.AccessLevel
--Here is the error
Msg 4104, Level 16, State 1, Procedure CreateUserOptions, Line 15
The multi-part identifier "t.Application" could not be bound.
Msg 4104, Level 16, State 1, Procedure CreateUserOptions, Line 15
The multi-part identifier "t.Task" could not be bound.
Msg 4104, Level 16, State 1, Procedure CreateUserOptions, Line 15
The multi-part identifier "t.DftAccessLevel" could not be bound.
Can I not multiply tables together like that and include a join?
You need a field to join the users table to the Tasks table.
SELECT u.[User], t.Application, t.Task, tl.Description
FROM SY.Tasks t
INNER JOIN SY.Users u --LEFT OUTER if it makes a difference
ON t.user = u.User --not sure if these fields are available maybe some type of userId?
LEFT OUTER JOIN SY.TaskLevels tl
ON t.Application = tl.Application
And t.Task = tl.Task AND t.DftAccessLevel = tl.AccessLevel
I think the problem is that in the second query, when you join the SY.Users table and the SY.TaskLevels table, you are referencing the SY.Tasks table - which is not part of the join.
Switch the Sy.Users table and the Sy.Tasks table around and your problem should be fixed.
It's because you're joining USERS to TaskLevels instead of Tasks to TaskLevels.
Try This:
SELECT u.[User], t.Application, t.Task, tl.Description
FROM SY.Users u, SY.Tasks t
LEFT OUTER JOIN SY.TaskLevels tl ON t.Application = tl.Application And t.Task = tl.Task AND t.DftAccessLevel = tl.AccessLevel
This will give you the cartesian product of users with (Tasks TaskLevels) though. So every user will have every task.