How to combine CASE statement with Inner Join for Alphanumeric OrderBY - sql

In this query, I am trying to select all distinct (alphanumeric) machine names and order them correctly (1,2,5,10,15 instead of 1,10,15,2,5). The CASE statement is proven to work when the LocalName is not joined by INNER JOIN, so I suspect this is where the problem lies.
SELECT DISTINCT MCGroup, VisionMachinePerformance.MCSAP, ZAssetRegister.LocalName
FROM [VisionMachinePerformance] INNER JOIN ZAssetRegister ON VisionMachinePerformance.MCSAP=ZAssetRegister.SAP_Number
ORDER BY
CASE WHEN PATINDEX('%[0-9]%',LocalName) > 1 THEN
LEFT(LocalName,PATINDEX('%[0-9]%',LocalName)-1)
ELSE LocalName END ,
CASE WHEN PATINDEX('%[0-9]%',LocalName) > 1 THEN
CAST(SUBSTRING(LocalName,PATINDEX('%[0-9]%',LocalName),LEN(LocalName)) as float)
ELSE NULL END
The error that is reported is "SQL Error (145): ORDER BY items must appear in the select list if SELECT DISTINCT is specified".
I have tried changing all references in the CASE statement to ZAssetRegister.LocalName and VisionMachinePerformance.LocalName without success.
Removing all of the CASE statement and ordering by LocalName does work, but with the wrong order as mentioned above (1,10,15,2,5).
Could anybody suggest how to make this work?
TIA!

You can separate both parts using a subquery:
SELECT * FROM (
SELECT DISTINCT MCGroup, VisionMachinePerformance.MCSAP, ZAssetRegister.LocalName
FROM [VisionMachinePerformance]
INNER JOIN ZAssetRegister ON VisionMachinePerformance.MCSAP=ZAssetRegister.SAP_Number
) DISTINCT_DATA
ORDER BY
CASE WHEN PATINDEX('%[0-9]%',LocalName) > 1
THEN LEFT(LocalName,PATINDEX('%[0-9]%',LocalName)-1)
ELSE LocalName END,
CASE WHEN PATINDEX('%[0-9]%',LocalName) > 1
THEN CAST(SUBSTRING(LocalName,PATINDEX('%[0-9]%',LocalName),LEN(LocalName)) as float)
ELSE NULL END

Related

Why does this not return 0

I have a query like:
select nvl(nvl(sum(a.quantity),0)-nvl(cc.quantityCor,0),0)
from RCV_TRANSACTIONS a
LEFT JOIN (select c.shipment_line_id,c.oe_order_line_id,nvl(sum(c.quantity),0) quantityCor
from RCV_TRANSACTIONS c
where c.TRANSACTION_TYPE='CORRECT'
group by c.shipment_line_id,c.oe_order_line_id) cc on (a.shipment_line_id=cc.shipment_line_id and a.shipment_line_id=7085740)
where a.transaction_type='DELIVER'
and a.shipment_line_id=7085740
group by nvl(cc.quantityCor,0);
The query runs OK, but returns no value. I want it to return 0 if there is no quantity found. Where have I gone wrong?
An aggregation query with a GROUP BY returns no rows if all rows are filtered out.
An aggregation query with no GROUP BY always returns one row, even if all rows are filtered out.
So, just remove the GROUP BY. And change the SELECT to:
select coalesce(sum(a.quantity), 0) - coalesce(max(cc.quantityCor), 0)
I may be wrong, but it seems you merely want to subtract CORRECT quantity from DELIVER quantity for shipment 7085740. You don't need a complicated query for that. Especially your GROUP BY clauses make no sense if that is what you are after.
One way to write this query would be:
select
sum(case when transaction_type = 'DELIVER' then quantity else 0 end) -
sum(case when transaction_type = 'CORRECT' then quantity else 0 end) as diff
from rcv_transactions
where shipment_line_id = 7085740;
I had a query like this and was trying to return 'X' when the item is not valid.
SELECT case when segment1 is not null then segment1 else 'X' end
--INTO v_orgValidItem
FROM mtl_system_items_b
WHERE segment1='1676001000'--'Jul-00'--l_item
and organization_id=168;
..but it was returning NULL.
Changed to use aggregation with no group by and now it returns 'X' when the item is not valid.
SELECT case when max(segment1) is not null then max(segment1) else 'X' end valid
--INTO v_orgValidItem
FROM mtl_system_items_b
WHERE segment1='1676001000'--'Jul-00'--l_item
and organization_id=168;--l_ship_to_organization_id_pb;
Here is another example, proving the order of operations really matters.
When there is no match for this quote number, this query returns NULL:
SELECT MAX(NVL(QUOTE_VENDOR_QUOTE_NUMBER,0))
FROM PO_HEADERS_ALL
WHERE QUOTE_VENDOR_QUOTE_NUMBER='foo.bar';
..reversing the order of MAX and NVL makes all the difference. This query returns the NULL value condition:
SELECT NVL(MAX(QUOTE_VENDOR_QUOTE_NUMBER),0)
FROM PO_HEADERS_ALL
WHERE QUOTE_VENDOR_QUOTE_NUMBER='foo.bar';

oracle sql error:distinct case

I am trying to select a distinct column from an oracle database,my code is:
select ID,distinct case when DM='ST1B' then MC else DM end from D_DZDY
but,it does not work.If i remove 'distinct',it works:
enter image description here
Anybody can help me with this problem?thanks a lot! :D
The syntax is select distinct. There is no distinct function or operator on a single column.
Perhaps you intend:
select distinct ID, (case when DM = 'ST1B' then MC else DM end)
from D_DZDY;
This will return distinct pairs of id and the case expression.
DISTINCT OPERATE ON ROW, YOU SHOULD USE THIS SYNTAX :
select distinct ID,(case when DM='ST1B' then MC else DM end) from D_DZDY
IF YOU JUST WANT DEFERMENT VALUES OF THE CASE STATEMENT YOU COULD USE THIS
select distinct (case when DM='ST1B' then MC else DM end) from D_DZDY

Using SQL SUM with Case statement containing inner SELECT

I have two tables, an Orders table which contains a list of a users orders and a OrderShippingCosts table which contains a price for shipping each item based on the OrderTypeID in the Orders table.
I am running a query like below to calculate the total shipping costs:
SELECT
SUM(CASE
WHEN OR.OrderTypeID = 1
THEN (SELECT CostOfShippingSmallParcel
FROM OrderShippingCosts)
ELSE (SELECT CostOfShippingBigParcel
FROM OrderShippingCosts)
END) AS TotalShippingCost
FROM
Orders AS OR
But I'm getting the following error:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery
Does anyone know what is wrong with my query?
Function SUM takes an expression on input, which evaluates into single data value, not a dataset. Expression definition from MSDN:
Is a combination of symbols and operators that the SQL Server Database Engine evaluates to obtain a single data value.
You trying to pass to SUM function a dataset (which is result of subquery), not a single data value. This is simplification of what you trying to query:
SELECT SUM(SELECT Number FROM SomeTable)
It is not valid. The valid query would be:
SELECT SUM(Value) FROM SomeTable
In your particular case looks like you missing JOIN. Your original logic will result in summary of entire OrderShippingCosts table for each row of Orders table. I think, it should be something like this:
SELECT
SUM
(
CASE
WHEN ord.OrderTypeID = 1 THEN ship.CostOfShippingSmallParcel
ELSE ship.CostOfShippingBigParcel
END
) TotalShippingCost
FROM Orders AS ord
JOIN OrderShippingCosts ship ON /* your search condition, e.g.: ord.OrderID = ship.OrderID */
By the way, it is not a good idea to use reserved symbols as aliases, names and so on. In your query you use OR as alias for Orders table. Symbol OR is reserved for logical or operation. If you really need to use reserved symbol, wrap it into [ and ] square braces. Look here and here for more details.
The error message is clear, you can avoid it with a join:
SELECT
SUM(CASE WHEN [OR].OrderTypeID = 1
THEN CostOfShippingSmallParcel
ELSE CostOfShippingBigParcel END) AS TotalShippingCost
FROM Orders [OR]
CROSS JOIN OrderShippingCosts
You can try like this...
SELECT
CASE WHEN OR.OrderTypeID = 1
THEN (SELECT SUM(CostOfShippingSmallParcel) FROM OrderShippingCosts)
ELSE (SELECT SUM(CostOfShippingBigParcel) FROM OrderShippingCosts) END AS TotalShippingCost
FROM Orders AS OR
Let me know
select sum (or.TotalShippingCost)
FROM
SELECT
(CASE WHEN OR.OrderTypeID = 1
THEN (SELECT CostOfShippingSmallParcel FROM OrderShippingCosts)
ELSE (SELECT CostOfShippingBigParcel FROM OrderShippingCosts) END) AS TotalShippingCost
FROM Orders AS OR
Try this
SELECT
ISNULL
(
SUM
(
CASE
WHEN O.OrderTypeID = 1 THEN C.CostOfShippingSmallParcel
ELSE C.CostOfShippingBigParcel END
), 0
) AS TotalShippingCost
FROM
Orders AS O LEFT JOIN
OrderShippingCosts C ON O.Id = C.OrderId -- Your releation id

Assign null if subquery retrieves multiple records. How can it be done?

I have the following query. I simplified it for demo purpose. I am using SQL Server - t-sql
Select tm.LocID = (select LocID from tblLoc tl
where tl.LocID = tm.LodID )
from tblMain tm
if the subquery returns multiple records, I like to assign tm.LocID to null else if there is only 1 record returned then assign it to tm.LocID. I am looking for a simple way to do this. Any help would be appreciated.
One way I can see is to have a CASE statement and check if (Count * > 1 ) then assign null else return the value but that would require a select statement within a select statement.
You have the right idea about using a case expression for count(*), but it will not require another subquery:
SELECT tm.LocID = (SELECT CASE COUNT(*) WHEN 1 THEN MAX(LocID) END
FROM tblLoc tl
WHERE tl.LocID = tm.LodID )
FROM tblMain tm
or just use a HAVING clause, like
Select tm.LocID = (select LocID from tblLoc tl
where tl.LocID = tm.LodID
group by locID
having count(*) = 1)
)
from tblMain tm
Your query above (and many of the other answers here) is a correlated subquery which will be very slow since it performs a separate aggregation query on each record. This following will address both your problem and potentially perform a bit better since the count happens in a single pass.
SELECT
CASE
WHEN x.locid IS NOT NULL THEN x.locid
ELSE NULL
END
FROM tblMain m
LEFT JOIN (
SELECT
locid
FROM tblLoc
GROUP BY locid
HAVING COUNT(1) = 1
) x
ON x.locid = m.locid
;
The above is in Postgres syntax (what I'm familiar with) so you would have to make it TSQL compatible.

Purpose of using syntax code "CASE GROUPING"

I don't understand the purpose of using syntax code "CASE GROUPING"?
Unfortunately, I don't have the database to review the sourcecode below.
SELECT
CASE GROUPING(st.stor_name) WHEN 0 THEN st.stor_name ELSE 'ALL' END AS Store,
CASE GROUPING(s.type) WHEN 0 THEN s.type ELSE 'ALL TYPES' END AS Type,
SUM(s.qty) AS TotalSold
FROM
(SELECT DISTINCT st.stor_id, t.type, 0 AS qty
FROM stores st CROSS JOIN titles t
UNION ALL
SELECT
s.stor_id,
t.type, s.qty
FROM sales s JOIN titles t ON s.title_id=t.title_id) s
JOIN stores st ON (s.stor_id=st.stor_id)
GROUP BY st.stor_name, s.type WITH CUBE
CASE is a conditional expression, like an if statement.
GROUPING is a function that:
Indicates whether a specified column expression in a GROUP BY list is aggregated or not. GROUPING returns 1 for aggregated or 0 for not aggregated in the result set. GROUPING can be used only in the SELECT list, HAVING, and ORDER BY clauses when GROUP BY is specified.