SQL IN statement not checking properly? - sql

I am working with a column/field from a table that has multiple "codes" or "ids" associated with it.
The table afacctbal has a column/field called afacbbalid, where the possibilities can be COST, PRN, or COLL.
What I am having trouble with is pulling the rows where COST is equal to 0 on the account.
I have tried a sub-queried SQL statement in the where clause, but returns a general error. Right now I am trying an IN statement but that doesn't seem to work either.
Here is what I've got:
select araccount.aracid as AccountID, arentity.arenst State, arentity.ARENNAME ClientName,
afaccount.afaccurbal CurrentBal, afacctbal.afacbcurbal PrincipalBal,
afacctbal.AFACBbalid
from araccount
inner join arrelationship on araccount.aracid = arrelationship.arrelacid
inner join arentity on arentity.arenid = arrelationship.ARRELENID
inner join afaccount on afaccount.afacacctid = araccount.ARACID
inner join afacctbal on afaccount.AFACKEY = afacctbal.AFACBACCTID
where afacctbal.afacbbalid in("COST",0)
and afaccount.AFACRATEID = "MN100"
and arentity.ARENST = "MN"
and araccount.araclstdte > "2013-04-01"
order by afaccount.afaccurbal
The trouble lies within my where clause
Here:
where afacctbal.afacbbalid in("COST",0)
How would I check for COST and check to see if its equal to 0?
AFACCTBAL TABLLE
Used Values:
afacbbalid -- balance id
afacbcurbal -- balance amount per balance id.
afaccount Table
Used Values:
afaccurbal -- current balance

You are using "COST" which is string and then 0 which is an integer. So, you need to cast both in the datatype which column afacctbal.afacbbalid has.

I think below query will work for your requirement -
select araccount.aracid as AccountID, arentity.arenst State, arentity.ARENNAME ClientName,
afaccount.afaccurbal CurrentBal, afacctbal.afacbcurbal PrincipalBal,
afacctbal.AFACBbalid
from araccount
inner join arrelationship on araccount.aracid = arrelationship.arrelacid
inner join arentity on arentity.arenid = arrelationship.ARRELENID
inner join afaccount on afaccount.afacacctid = araccount.ARACID
inner join afacctbal on afaccount.AFACKEY = afacctbal.AFACBACCTID
where ((afacctbal.afacbbalid ='COST'
and afaccurbal.currentBal = 0) or
(afacctbal.afacbbalid ='PRN'
and afaccurbal.currentBal > 0))
and afaccount.AFACRATEID = "MN100"
and arentity.ARENST = "MN"
and araccount.araclstdte > "2013-04-01"
order by afaccount.afaccurbal

Related

Oracle SQL - how to NOT SHOW athlete name that apears only once

created a view called winners, it contains the columns: athlete_name,year,medal_won
its basicly athletes that won olympic medal and the year,
it look like that,
data base is in live sql: https://livesql.oracle.com/apex/f?p=590:1000:0
select distinct year,athlete_name,medal
from olym.olym_medals
join olym.olym_athlete_games on olym_athlete_games.id = olym_medals.athlete_game_id
join olym.olym_nations on olym_nations.id = olym_athlete_games.nation_id
join olym.olym_games on olym_games.id = Olym_athlete_games.game_id
join olym.olym_athletes on olym_athletes.id = olym_athlete_games.athlete_id
order by athlete_name
as you can see some name show only once and some names are showing more than once, i want to get rid off all lines of those who show ONLY ONCE, please help me.
thank you!
if i have understand your problem, must group your data,
select year,athlete_name,medal, count(*) "number of Medals"
from olym.olym_medals
join olym.olym_athlete_games on olym_athlete_games.id = olym_medals.athlete_game_id
join olym.olym_nations on olym_nations.id = olym_athlete_games.nation_id
join olym.olym_games on olym_games.id = Olym_athlete_games.game_id
join olym.olym_athletes on olym_athletes.id = olym_athlete_games.athlete_id
group by year,athlete_name,medal;
If I followed you correctly, you can use window functions:
select *
from (
select og.year, oa.athlete_name, om.medal, count(*) over(partition by oa.id) cnt
from olym.olym_medals om
join olym.olym_athlete_games oag on oag.id = om.athlete_game_id
join olym.olym_nations ona on ona.id = oag.nation_id
join olym.olym_games og on og.id = oag.game_id
join olym.olym_athletes oa on oa.id = oag.athlete_id
) t
where cnt > 1
order by athlete_name
Notes:
I am unsure why you were using distinct in the first place, so I removed it (I suspect it is actually not needed)
I added table aliases to shorten the query, and prefixed the columns in the select clause with the table they belong to (you might want to review that) - these are best practices when dealing with multi-table queries
Use GROUP BY and HAVING COUNT(*) > 1:
SELECT year,
athlete_name,
medal
FROM olym.olym_medals
INNER JOIN olym.olym_athlete_games
ON olym_athlete_games.id = olym_medals.athlete_game_id
INNER JOIN olym.olym_nations
ON olym_nations.id = olym_athlete_games.nation_id
INNER JOIN olym.olym_games
ON olym_games.id = Olym_athlete_games.game_id
INNER JOIN olym.olym_athletes
ON olym_athletes.id = olym_athlete_games.athlete_id
GROUP BY
year,
athlete_name,
medal
HAVING COUNT(*) > 1
ORDER BY athlete_name

How to Sum Entire Column with SQL

I'm trying to Sum an entire column in SQL. The code below sums each row, but instead I just want a total row. My guess is it has to be done with GROUP BY, but the only way the query works is if I use Share_Type or Balance, neither of which sums the column. I also tried adding the CASE statement to the Group by (by leaving off 'AS MoneyMaxBalance" but I get an error message.
SELECT
CASE
WHEN SHARE_TYPE = 57 THEN SUM(BALANCE) ELSE 0
END AS MoneyMaxBalance
FROM SHARE
INNER JOIN ACCOUNT ON SHARE.MEMBER_NBR = ACCOUNT.MEMBER_NBR AND
SHARE.SHARE_NBR = ACCOUNT.ACCOUNT_NBR
INNER JOIN PRODUCT ON ACCOUNT.PRODUCT_CODE = PRODUCT.PRODUCT_CODE
GROUP BY SHARE_TYPE
If you just want one row, don't use group by:
SELECT SUM(BALANCE) AS MoneyMaxBalance
FROM SHARE s INNER JOIN
ACCOUNT a
ON s.MEMBER_NBR = a.MEMBER_NBR AND
s.SHARE_NBR = a.ACCOUNT_NBR INNER JOIN
PRODUCT p
ON a.PRODUCT_CODE = p.PRODUCT_CODE
WHERE SHARE_TYPE = 57;
SELECT SUM(CASE WHEN SHARE_TYPE = 57 THEN BALANCE ELSE 0 END) AS MoneyMaxBalance
FROM SHARE s
INNER JOIN ACCOUNT a ON s.MEMBER_NBR = a.MEMBER_NBR AND s.SHARE_NBR = a.ACCOUNT_NBR
INNER JOIN PRODUCT p ON a.PRODUCT_CODE = p.PRODUCT_CODE
Hope this Query Works fine for your case:

Using COALESCE with JOIN on a different database column

Trying to populate the location column of a query and was hoping that the use of the COALESCE function would help me get what I want.
SELECT OrderItem.Code AS ItemCode, MAX(COALESCE(OrderItem.Location, [Picklist].[dbo].[ItemData].InventoryLocation)) AS Location, SUM(OrderItem.Quantity) AS Quantity, MAX(Store.StoreName) AS Store
FROM OrderItem
INNER JOIN [Order] ON OrderItem.OrderID = [Order].OrderID
INNER JOIN [Store] ON [Order].StoreID = [Store].StoreID
LEFT JOIN [AmazonOrder] ON [AmazonOrder].OrderID = [Order].OrderID
JOIN [Picklist].[dbo].[ItemData] ON [Picklist].[dbo].[ItemData].[InventoryNumber] = [OrderItem].[Code]
WHERE (CASE WHEN [Order].[LocalStatus] = 'Recently Downloaded' AND [AmazonOrder].FulfillmentChannel = 2 THEN 1
WHEN [Order].[LocalStatus] = 'Recently Downloaded' AND [Store].StoreName != 'Amazon' THEN 1 ELSE 0 END ) = 1
GROUP BY OrderItem.Code
ORDER BY ItemCode
There will not be a location when the Store is Amazon so I need to Join on another table in another database. I don't believe I'm using this correctly. Also I do get the right Location results returned if I use :
SELECT InventoryLocation From [Picklist].[dbo].[ItemData] WHERE InventoryNumber = 'L1201-2W-EA'
Perhaps this is more like the query that you want:
SELECT oi.Code AS ItemCode, COALESCE(oi.Location, id.InventoryLocation) AS Location,
oi.Quantity, s.StoreName AS Store
FROM OrderItem oi INNER JOIN
[Order] o
ON oi.OrderID = o.OrderID INNER JOIN
[Store]
ON o.StoreID = s.StoreID LEFT JOIN
AmazonOrder ao
ON ao.OrderID = o.OrderID JOIN
[Picklist].[dbo].[ItemData] id
ON id.InventoryNumber = oi.[Code]
WHERE o.LocalStatus = 'Recently Downloaded' AND
(ao.FulfillmentChannel = 2 OR s.StoreName <> 'Amazon')
ORDER BY ItemCode
Here are the changes:
Removed the aggregation. It does not seem to be part of the question.
Introduced table aliases, so the query is easier to write and to read.
Simplified the logic in the where clause.
As the comment above says, the max seems somewhat strange, an arbitrary aggregation no doubt due to one of the joins bringing back more information than you might of expected.
Then the statement has a few issues:
The coalesce is using two fields, neither if which is in a left join, only the AmazonOrder is left joined, so that seems a bit strange, that would only work if the first field in the coalesce (OrderItem.Location) is nullable - which it might be, there is no schema posted.
The left join itself is an inner join in disguise at present - within the where clause you have given explicit conditions on a field from that table - AND [AmazonOrder].FulfillmentChannel = 2 - if the record was actually missing the left join would return null for that field, and the where clause would then drop it out of the results. If you want this to properly work as a left join, any condition on fields from that table must move into the join condition, or the where clause itself must allow for that field being null (explicitly or using a coalesce.)
SELECT OrderItem.Code AS Code,
CASE WHEN (LEN(ISNULL(MAX([OrderItem].[Location]),'')) = 1)
THEN MAX([OrderItem].[Location])
ELSE MAX([Picklist].[dbo].[ItemData].InventoryLocation)
END AS Location,
SUM(OrderItem.Quantity) AS Quantity,
MAX(Store.StoreName) AS Store
FROM OrderItem
INNER JOIN [Order] ON OrderItem.OrderID = [Order].OrderID
INNER JOIN [Store] ON [Order].StoreID = [Store].StoreID
LEFT JOIN [AmazonOrder] ON [AmazonOrder].OrderID = [Order].OrderID
LEFT JOIN [Picklist].[dbo].[ItemData] ON [Picklist].[dbo].[ItemData].[InventoryNumber] = [OrderItem].[Code] OR
[Picklist].[dbo].[ItemData].[MediaCreator] = [OrderItem].[Code]
WHERE [Order].LocalStatus = 'Recently Downloaded' AND (AmazonOrder.FulfillmentChannel = 2 OR Store.StoreName <> 'Amazon')
GROUP BY OrderItem.Code
ORDER BY OrderItem.Code
Decided to go with case statement on location column route because I could not get COALESCE to work for me. Schema, some not all data, at SQLFiddle.
I guess if someone gets COALESCE to work I'll change the answer?
#Gordon Linoff I used the re-written WHERE clause because it looked cleaner than using the CASE statement. It worked and guessed there was a simpler way to go about it but was more worried about getting COALESCE to work. As for the Aliases sometimes I like to use them but in this case since there was a lot of tables I like to code out what I'm actually working in. Just my preference .

Having Asking for Group By clause and not allowing it

I am trying to include a selection for the MAX date range in my where clause. I am using Having to bring it in, but it errors out saying that "Column 'dbo.PURCHLINE.PURCHID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." But it won't let me group, throwing other errors. Maybe i'm approaching this wrong. Essentially, I need to get the latest date in in a set of columns for this query:
Select
PURCHLINE.PURCHID as 'PO'
,SUBSTRING(Cast(Max(VENDPACKINGSLIPJOUR.DELIVERYDATE) as varChar), 0, 12) as 'DeliveryDate'
,PURCHLINE.QTYORDERED as 'QtyOrdered'
FROM dbo.PURCHLINE
INNER JOIN dbo.INVENTTABLE
ON dbo.PURCHLINE.ITEMID = dbo.INVENTTABLE.ITEMID
INNER JOIN dbo.INVENTITEMGROUP
ON dbo.INVENTTABLE.ITEMGROUPID = dbo.INVENTITEMGROUP.ITEMGROUPID
INNER JOIN dbo.INVENTPOSTING
ON dbo.INVENTITEMGROUP.ITEMGROUPID = ITEMRELATION
INNER JOIN dbo.PURCHTABLE
ON dbo.PURCHLINE.PURCHID = dbo.PURCHTABLE.PURCHID
INNER JOIN dbo.LEDGERTABLE
ON LEDGERACCOUNTID = ACCOUNTNUM
INNER JOIN VENDPACKINGSLIPJOUR
on VENDPACKINGSLIPJOUR.PURCHID = PURCHLINE.PURCHID
WHERE
dbo.PURCHLINE.PURCHSTATUS = 3 --open Order
AND dbo.PURCHLINE.PURCHASETYPE = 3 --Purchase Order
AND dbo.PURCHLINE.DIMENSION IN (#department)
AND INVENTACCOUNTTYPE = 0 --Purchase Packing Slip
AND PURCHLINE.DIMENSION2_ = #division
HAVING Max(VENDPACKINGSLIPJOUR.DELIVERYDATE) between #start and #end
You have an aggregate, so you'll need to group on the nonaggregate fields:
GROUP BY
PURCHLINE.PURCHID
,PURCHLINE.QTYORDERED
This goes before the HAVING clause.

SQL Query to retrieve single record per filter

I have the following query:
SELECT min(salesorder.SOM_SalesOrderID) AS salesorder,
Item.IMA_ItemID,
Item.IMA_ItemName,
Customer.CUS_CorpName,
WK.WKO_WorkOrderID,
min(WK.WKO_OrigRequiredDate),
WK.WKO_WorkOrderTypeCode,
min(WK.WKO_RequiredDate),
max(WK.WKO_LastWorkDate),
min(wk.WKO_RequiredQty),
wk.WKO_MatlIssueDate,
min(SalesOrderDelivery.SOD_RequiredQty),
Item.IMA_ItemTypeCode,
Item.IMA_OnHandQty,
min(SalesOrderDelivery.SOD_PromiseDate),
min(WO.woo_operationseqID) AS seqid
FROM SalesOrder
INNER JOIN SalesOrderLine ON SalesOrder.SOM_RecordID = SalesOrderLine.SOI_SOM_RecordID
INNER JOIN SalesOrderDelivery ON SalesOrderLine.SOI_RecordID = SalesOrderDelivery.SOD_SOI_RecordID,
WO.
INNER JOIN Item ON SalesOrderLine.SOI_IMA_RecordID = Item.IMA_RecordID
INNER JOIN WKO wk ON Item.IMA_ItemID = WK.WKO_ItemID
INNER JOIN Customer ON SalesOrder.SOM_CUS_RecordID = Customer.CUS_RecordID
INNER JOIN woo WO ON WO.WOO_WorkOrderID = WK.WKO_WorkOrderID
WHERE wk.WKO_StatusCode = 'Released'
AND WO.WOO_StatusCode IS NULL
AND SalesOrderDelivery.SOD_ShipComplete = 'false'
GROUP BY WK.WKO_WorkOrderID,
Item.IMA_ItemID,
Item.IMA_ItemName,
Customer.CUS_CorpName,
WK.WKO_WorkOrderTypeCode,
wk.WKO_MatlIssueDate,
Item.IMA_ItemTypeCode,
Item.IMA_OnHandQty
I need 1 record returned for each wk.wko_workorderid. There is a field that is not included that I'm not sure how to get. I need to retrieve the woo.woo_workcenterid that corresponds to min(WO.woo_operationseqID)as seqid. I cannot include it in the general query since there are multiple workcenterids in the table and I only want the specific one that is part of the min operation sequence record.
Any help would be appreciated.