How to sort before using STUFF in SSRS - sql-server-2008

I have 2 different values I'm trying to STUFF here. It is Quantity + Price. For example: 1-$0.36; 100-$0.29; 25-$0.31. How can I have it sort by Quantity before being stuffed? (1,25,100 instead of 1,100,25) I did come across this link Sort data before concatenating using STUFF FOR XML, but it dealt with 1 value and I'm dealing with 2 values
SELECT STUFF(
(SELECT DISTINCT TOP (5)
'; ' + (CAST(FLOOR(CASE WHEN PCFBD.Quantity IS NOT NULL THEN PCFBD.Quantity ELSE 1 END) AS VARCHAR) + '-$' + CAST(REPLACE(REPLACE(RTRIM(REPLACE(
CASE WHEN PCF.PriceMethod = 0 THEN ROUND(I.CdCost / (100 - PCF.FormulaPercent) * 100, 2)
WHEN PCFBH.PriceFormula = 2 AND PCFBD.FormulaPercent IS NULL THEN ROUND(I.CdCost / (100 - PCF.FormulaPercent) * 100, 2)
WHEN PCFBH.PriceFormula = 2 AND PCFBD.FormulaPercent IS NOT NULL THEN ROUND(I.CdCost / (100 - PCFBD.FormulaPercent) * 100, 2)
WHEN PCFBH.PriceFormula = 1 THEN ROUND((I.ListPrice * (100 - PCFBD.FormulaPercent)) * .01,2)
ELSE NULL END, '000' ,'')), ' ','0') + '', '. ', '') AS VARCHAR))
FROM Item AS I
INNER JOIN PriceContractFamily AS PCF ON I.FamilyId = PCF.FamilyId
AND I.ItemStatus IN (0, 5)
INNER JOIN StockItem SI ON I.ItemId = SI.ItemId
AND SI.WarehouseId = '502E5876-C26B-4E11-8B88-AFE0C34ECF0D'
LEFT OUTER JOIN PriceContractFamilyBracketHeader AS PCFBH ON PCF.PriceContractFamilyId = PCFBH.PriceContractFamilyId
LEFT OUTER JOIN PriceContractFamilyBracketDetail AS PCFBD ON PCFBH.BracketHeaderId = PCFBD.BracketHeaderId
WHERE I.ListPrice = #ListPrice
AND LEFT(I.ItemNumber, 6) = #ItemNumber
AND PCF.PriceContractId = #PriceContractId
FOR XML PATH('')),1, 2, '') AS QtyPrice

You should be able to add an ORDER BY before the FOR XML PATH statement.

Related

Recursion in Mysql with as

There is a trip table with flights containing columns with the beginning and end of the route. It is necessary to organize a search for a route with several transfers. I can't figure out what my mistake is (error at line 21)?
with RoutesCTE as
(
select concat(airport_from + '->' + airport_to) as Route
,0 as TransfersCount
,airport_from
,airport_to
from trip
union all
select concat(r.Route + '->' + r1.airport_to) as Route
,TransfersCount + 1
,r.airport_from
,r1.airport_to
from RoutesCTE r
join trip r1
on r.airport_to = r1.airport_from
and r1.airport_to <> r.airport_from
and REGEXP_INSTR('%'+r1.airport_to+'%', r.Route) = 0
)
select Route
from RoutesCTE
where airport_from = 'MVO'
and airport_to = 'NOV'
and TransfersCount <= 2;

MySql get balance of accounts

i want to calculate the balance of 3 accounts.
I have 2 tables:
accounts with id, name and start-balance
transactions with value, charge-account, type and paid
To calculate the balance i have to add the start-balance (from accounts) with alle the transaction-values where charge-account = account-id, paid = 1 and type = 1. Then i have to subtract (correct word?) all the transaction-values where charge-account = account-id, paid = 1 and type = 0
At the end, if everything would work i just want to see what balance the accounts have right now.
i tried this query but i get wrong results, it looks like it adds the start-balance multiple times...
SELECT
SUM(IF(a.id = 1, IF(t.type = 1 AND t.charge_account = 1, t.value, 0) - IF(t.type = 0 AND t.charge_account = 1, t.value, 0), 0) + a.start-balance) as "balanc_1",
SUM(IF(a.id = 2, IF(t.type = 1 AND t.charge_account = 2, t.value, 0) - IF(t.type = 0 AND t.charge_account = 2, t.value, 0), 0) + a.start-balance) as "balance_2",
SUM(IF(a.id = 3, IF(t.type = 1 AND t.charge_account = 3, t.value, 0) - IF(t.type = 0 AND t.charge_account = 3, t.value, 0), 0) + a.start-balance) as "balance_3"
FROM test.transactions t, test.accounts a
WHERE t.paid = 1;
transactions:
accounts:
how it should be like:
SELECT a.id,
MAX ( a.`start-balance` ) +
SUM ( CASE WHEN t.type = 1 then t.value
WHEN t.type = 2 then -t.value
ELSE 0
END ) as balance
FROM accounts a
JOIN transactions t
ON a.id = t.`charge-account`
WHERE a.id IN (1,2,3)
AND t.paid = 1
GROUP BY id
You need to use UNION and then group by account id
select accountid, sum(amount ) as amount from (
select accountid, startamount as amount from accounts
union
select accountid, transactionamount from transactions WHERE ....
) t
group by accountid

MySQL Multiple Case When Exists Statement

I have two tables. Let's call it: SEATS and SEAT_ALLOCATION_RULE table.
Below are the table schema:
CREATE TABLE IF NOT EXISTS `SEATS` (
`SeatID` int(11) NOT NULL AUTO_INCREMENT,
`SeatName` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`SeatID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
INSERT INTO `SEATS` (`SeatID`, `SeatName`) VALUES
(1, 'Super VIP'),
(2, 'VIP'),
(3, 'Business'),
(4, 'Economy'),
(5, 'Standing');
CREATE TABLE IF NOT EXISTS `SEAT_ALLOCATION_RULE` (
`SeatID` int(11) NOT NULL DEFAULT '0',
`Origin` varchar(50) NOT NULL DEFAULT '0',
`Destination` varchar(50) NOT NULL DEFAULT '',
`Passenger_Type` varchar(25) NOT NULL DEFAULT '',
PRIMARY KEY (`SeatID`,`Origin`,`Destination`,`Passenger_Type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `SEAT_ALLOCATION_RULE` (`SeatID`, `Origin`, `Destination, `Passenger_Type`) VALUES
(1, 'Malaysia','',''),
(2, 'Malaysia','Singapore',''),
(3, 'Malaysia','Singapore','Senior_Citizen'),
(4, 'Bangkok','Japan','Student'),
(5, 'Cambodia','China','Senior_Citizen');
SEAT_ALLOCATION_RULE table determines which seat should a passenger be assigned to based on the following order in priority:
1. Origin, destination, and passenger_type match
2. Origin and destination match
3. Origin match
It means that if all the fields (origin, destination, and passenger_type) match, it should take higher priority than if it is just two fields match and so on. If a column is empty, it is considered as unspecified and hence has lower priority. So, for example:
If the Origin is Malaysia, Destination is Singapore, and Passenger_Type is Senior_Citizen, it should return seatID 3
If the Origin is Malaysia, Destination is Singapore, and Passenger_Type is Student, it should return seatID 2 (since it only match Origin and Destination)
If the Origin is Malaysia, Destination is US, and Passenger_Type is Student, it should return seatID 1 (since it only match Origin).
Now, based on the rules above, if the origin is Malaysia, destination is Singapore, and Passenger_Type is student, the query to return seatID is as follow:
SELECT s.SeatID, s.SeatName
FROM SEATS s
WHERE
CASE WHEN EXISTS(
select 1
from SEAT_ALLOCATION_RULE r
where s.SeatID = r.SeatID
AND r.Origin = 'Malaysia'
AND r.Destination = 'Singapore'
AND r.Passenger_Type='Student') Then 1
WHEN EXISTS(
select 1
from SEAT_ALLOCATION_RULE r
where s.SeatID = r.SeatID
AND r.Origin = 'Malaysia'
AND r.Destination = 'Singapore'
AND r.Passenger_Type='') Then 1
WHEN EXISTS(
select 1
from SEAT_ALLOCATION_RULE r
where s.SeatID = r.SeatID
AND r.Origin = 'Malaysia'
AND r.Destination = ''
AND r.Passenger_Type='') Then 1 END
However, the query above does not work as it will return seatID 1 and 2, but the expected output is only seatID 2 (since origin and destination matches and it takes higher precedence). Can someone help to correct my SQL query?
This should do the trick:
select seatid
from seat_allocation_rule sar
order by ((sar.origin = :origin) << 2) + ((sar.destination = :destination) << 1) + (sar.passenger_type = :passenger_type) desc,
((sar.origin <> '') << 2) + ((sar.destination <> '') << 1) + (sar.passenger_type <> '') asc
limit 1
To understand how:
create table testcase (
origin varchar(255),
destination varchar(255),
passenger_type varchar(255),
expected_seat int(11)
);
insert into testcase values ('Malaysia','Singapore','Senior_Citizen',3),
('Malaysia','Singapore','Student',2),
('Malaysia','US','Student',1);
select * from (
select tc.*,
sar.seatid,
case when sar.seatid = tc.expected_seat then 'Y' else '-' end as pass,
((sar.origin = tc.origin) << 2)
+ ((sar.destination = tc.destination) << 1)
+ ((sar.passenger_type = tc.passenger_type) << 0) as score,
((sar.origin <> '') << 2)
+ ((sar.destination <> '') << 1)
+ ((sar.passenger_type <> '') << 0) as priority
from seat_allocation_rule sar
cross join testcase tc
) x order by expected_seat desc, score desc, priority asc;
This fixes the existing SQL:
SELECT DISTINCT s.SeatID, s.SeatName
FROM SEATS s
LEFT JOIN SEAT_ALLOCATION_RULE r ON r.SeatID = s.SeatID
AND r.Origin = 'Malaysia'
AND (
(r.Destination = 'Singapore' AND r.Passenger_Type IN ('Student', ''))
OR
(r.Destination = '' AND r.Passenger_Type = '')
)
WHERE r.SeatID IS NOT NULL
But it's only a partial solution, and it's hand-coding logic you really want to apply based solely on the data.
A complete solution will use hypothetical inputs for your passenger's ticket info to produce all eligible seats. This is a great use of lateral joins/apply, which are sadly lacking in MySql (all of their major competitors have had these for at least two release cycles, along with other gems that are absent from the current MySql release like windowing functions, ctes, full joins... I could go on). Here's how I'd do it in Sql Server:
SELECT p.PassengerID, s.SeatID, s.SeatName
FROM Passenger p
CROSS APPLY (
SELECT TOP 1 r.SeatID
FROM SEAT_ALLOCATION_RULE r
WHERE COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
ORDER BY
CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END DESC
) r
INNER JOIN SEATS s ON s.SeatID = r.SeatID
WHERE p.PassengerID = /* passenger criteria here */
I know the Sql Server solution isn't much immediate help to you, but perhaps it will suggest a better MySql solution.
Without APPLY, the only way I know to do this is to first compute the MAX() match count for your passengers (how many parts of the rules match):
SELECT p.PassengerID,
MAX(CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END) AS MatchCount
FROM Passenger p
INNER JOIN SEAT_ALLOCATION_RULE r ON COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
GROUP BY p.PassengerID
And then use that to filter down to results that have the same number of matches:
SELECT p
FROM Passenger p
INNER JOIN ( /* matchecounts */
SELECT p.PassengerID,
MAX(CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END) AS MatchCount
FROM Passenger p
INNER JOIN SEAT_ALLOCATION_RULE r ON COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
GROUP BY p.PassengerID
) m ON m.PassengerID = p.PassengerID
INNER JOIN SEAT_ALLOCATION_RULE r ON COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
INNER JOIN SEATS s ON s.SeatID = r.SeatID
WHERE m.MatchCount =
(CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END)
AND p.PassengerID = /* Passenger criteria here */
Which repeats a lot of code as well as effort in the DB, and is not very efficient. You can repeat the passenger criteria in the nested query, but that would only help a little. This option might also return multiple records for a passenger if they match two rules equally, though you can solve this easily enough with a GROUP BY expression.
In either case, note you can improve performance and simplify code by using actual NULL values instead of empty strings for missing parts of the SEAT_ALLOCATION_RULE table.

SQL CONCAT Function

I would like to create a Concate like:
CONCAT(OEEL.orderno+'-'+OEEL.ordersuf+'-'+OEEL.prodcat) AS "Unique"
SELECT OEEL.invoicedt, UCASE(OEEL.whse) AS Whse, OEEL.orderno, OEEL.ordersuf, OEEL.custno, UCASE(OEEL.shipto) AS Shipto, UCASE(OEEL.slsrepin) AS Slsrepin,
UCASE(OEEL.slsrepout) AS Slsrepout, OEEL.returnfl, OEEL.netamt, OEEL.wodiscamt, OEEL.discamtoth, OEEL.qtyship, OEEL.commcost, ICSS.csunperstk,
UCASE(ICSD.name) AS Name, UCASE(ICSD.region) AS Region, UCASE(OEEL.prodcat) AS Prodcat, UCASE(SASTA.descrip) AS Descrip, UCASE(OEEL.transtype)
AS Transtype, UCASE(ARSS.user2) AS User2, OEEL.transdt, ICSS.transdt AS "ICSS.Transdt", ICSD.transdt AS "ICSD.Transdt", SASTA.transdt AS "SASTA.Transdt",
ARSS.transdt AS "ARSS.Transdt", { fn CURDATE() } AS CURDATE1, { fn CURTIME() } AS CURTIME2,
CASE WHEN OEEL.returnfl = '0' THEN (OEEL.netamt - OEEL.wodiscamt - OEEL.discamtoth) ELSE (- 1 * (OEEL.netamt - OEEL.wodiscamt - OEEL.discamtoth))
END AS "SALES", CASE WHEN OEEL.returnfl = '0' THEN (OEEL.qtyship * OEEL.commcost * NVL(ICSS.csunperstk, 1))
ELSE (- 1 * OEEL.qtyship * OEEL.commcost * NVL(ICSS.csunperstk, 1)) END AS "COST",
(CASE WHEN OEEL.returnfl = '0' THEN (OEEL.netamt - OEEL.wodiscamt - OEEL.discamtoth) ELSE (- 1 * (OEEL.netamt - OEEL.wodiscamt - OEEL.discamtoth)) END)
- (CASE WHEN OEEL.returnfl = '0' THEN (OEEL.qtyship * OEEL.commcost * NVL(ICSS.csunperstk, 1))
ELSE (- 1 * OEEL.qtyship * OEEL.commcost * NVL(ICSS.csunperstk, 1)) END) AS GP
FROM { oj { oj { oj { oj PUB.oeel OEEL LEFT OUTER JOIN
PUB.icss ICSS ON OEEL.cono = ICSS.cono AND OEEL.shipprod = ICSS.prod AND OEEL.icspecrecno = ICSS.icspecrecno } LEFT OUTER JOIN
PUB.icsd ICSD ON OEEL.cono = ICSD.cono AND OEEL.whse = ICSD.whse } LEFT OUTER JOIN
PUB.sasta SASTA ON OEEL.cono = SASTA.cono AND OEEL.prodcat = SASTA.codeval } LEFT OUTER JOIN
PUB.arss ARSS ON OEEL.cono = ARSS.cono AND OEEL.custno = ARSS.custno AND OEEL.shipto = ARSS.shipto }
WHERE (OEEL.cono = 1) AND (OEEL.invoicedt BETWEEN { d '2014-06-02' } AND { d '2014-06-03' }) AND (SASTA.codeiden IN ('C', 'c'))
ORDER BY OEEL.custno, OEEL.shipto, OEEL.prodcat
The function has + (which in MySQL is not a concatenation symbol) between the variables.
Try:-
CONCAT_WS('-', OEEL.orderno, OEEL.ordersuf, OEEL.prodcat) AS `Unique`
CONCAT_WS does a concatenation With Separator .the first parameter is the separator with the others concatenated together.

How to sum all titles even others are empty

my query objective is to sum all the fields from (3) tables but i have some problem in generating the final_total_sum output if some of the other titles empty the final_total_sum is empty....but if all titles are not empty my query generate final_total_sum(output).
I wan to do is even other titles are empty my query can still generate a final_total_sum(output).
http://s38.photobucket.com/user/eloginko/media/output_zpsfcab9d54.png.html
current query:
SELECT *,
ROUND(interview_sum +
other_sum +
edu_attain2_sum +
experience2_sum +
trainings2_sum +
eligibility2_sum) AS final_total_sum
FROM (
SELECT
ROUND((SELECT SUM(t2.inttotal)
FROM app_interview2 AS t2
WHERE t2.atic = t.atic)/7,1)
AS interview_sum,
ROUND((SELECT SUM(o2.ototal)
FROM other_app2 AS o2
WHERE o2.oaic = t.atic)/7,1)
AS other_sum,
ROUND((SELECT SUM(s1.edu_attain2)
FROM qual_stan2 AS s1
WHERE s1.oaic2 = t.atic)/7,1)
AS edu_attain2_sum,
ROUND((SELECT SUM(s2.experience2)
FROM qual_stan2 AS s2
WHERE s2.oaic2 = t.atic)/7,1)
AS experience2_sum,
ROUND((SELECT SUM(s3.trainings2)
FROM qual_stan2 AS s3
WHERE s3.oaic2 = t.atic)/7,1)
AS trainings2_sum,
ROUND((SELECT SUM(s4.eligibility2)
FROM qual_stan2 AS s4
WHERE s4.oaic2 = t.atic)/7,1)
AS eligibility2_sum,
t.atid,
t.atic,
t.atname,
t.region,
t.town,
t.uniq_id,
t.position,
t.salary_grade,
t.salary
FROM app_interview2 AS t
WHERE uniq_id = '$q'
GROUP BY t.atname
HAVING COUNT(DISTINCT t.atic)) subq
Try:
ROUND( ifnull(interview_sum,0) +
ifnull(other_sum,0) +
ifnull(edu_attain2_sum,0) +
ifnull(experience2_sum,0) +
ifnull(trainings2_sum,0) +
ifnull(eligibility2_sum,0)) AS final_total_sum
In SQL x + NULL always gives NULL, ifnull function converts nulls to 0
use like SUM(ifnull(t2.inttotal,0))