Wrong data pulled from database in cakePHP - sql

I am working with cakePHP and am having an issues with microsoft sql server. Basically, I am pulling data about the success rates of different campains. Once of the lines calculates the 'revenue per flyer.'
SUM(o.TotalPrice) / COUNT(cc.CustomerID) AS RevPerFlyer
The issue is, cakePHP is calculating this value wrong. Here is my entire query:
SELECT
c.State,
'?' AS FlyersMailed,
COUNT(o.CampaignCustomerID) AS Orders,
SUM(o.TotalPrice) AS TotalRevenue,
SUM(o.TotalPrice) / COUNT(cc.CustomerID) AS RevPerFlyer
FROM Customer c
INNER JOIN CampaignCustomer cc
ON c.CustomerID = cc.CustomerID
LEFT JOIN CustomerOrder o
ON cc.CampaignCustomerID = o.CampaignCustomerID
WHERE 1=1
AND OrderStatusID NOT IN (4,9,10,11,13)
AND cc.CampaignID = 8
GROUP BY
State
ORDER BY
When I run this directly in sql server,I get the correct data.
Example: Here is
RevPerFlyer for the state AK: 73.924
However, when I run this same exact sql from cake, this is what I get:
RevPerFlyer for the state AK: 7.2502
Does anyone know what the problem may be? Maybe a problem with sql server?
Thanks in advance!

Related

Eloquent sum of derived column in select and also where clause

I have a table sales which has a related receipts table.
A sale can have many receipts. If the sum of the receipts is less than the sales amount then there is a balance outstanding.
I have the SQL that works just how I want. Having headaches trying to shoehorn this into eloquent.
SELECT `sales`.`id`, `sales`.`created_at`,`sales`.`updated_at`,`sales`.`sales_date`,`sales`.`gross`, `sales`.`net_amount`,`sales`.`vat_amount`,`sales`.`vat_rate`,`sales`.`description`,
(SELECT SUM(receipt_gross_amount) as received_gross FROM `receipts` INNER JOIN `sales` WHERE `receipts`.`sales_id` = `sales`.`id`) as received
FROM `sales`
) as unsettled_invoices
WHERE unsettled_invoices.gross > COALESCE(unsettled_invoices.received,0)
I won't bore you with what I have tried already as it's not relevant and just causes php to hang and issue "killed" in the command line...
This seems to do the job ...
$unsettledsalessentries = DB::table('sales')
->leftjoin('receipts', 'sales.id','=', 'receipts.sales_id')
->select('sales.id','sales.gross','sales.description',DB::raw('SUM(COALESCE(receipts.receipt_gross_amount,0)) as total_receipts'))
->groupBy('sales.id','sales.gross','sales.description')
->havingRaw('sales.gross > total_receipts')
->get();

MS Access 2016 Error: "Multi-level group by not allowed"

i'm stuck at another point in my little Access 2016 Database. My code looks like the following and i know it probably isn't the cleanest solution but i'm kinda new to this and i tried to educate myself and get some help here already.
I'm trying to play around with the reports now a little bit and i am using this test query which returns all entries of two tables joined together.
As far as i could find out I have this one subquery included that returns the prvious day inventory for each record and that is most likely the cause of my error. I found a possible solution with adding SELECT * FROM at the beginning of my code but i get a Syntax error when i do that and i'm not sure how to solve this problem.
here's my code
SELECT Stations.StationName, Product.ProductName, GasInventoryTransactions.TransactionDate, (SELECT TOP 1 Dupe.ActualInventory FROM GasInventory AS Dupe WHERE Dupe.StationID = Stations.StationID AND Dupe.ProductID = Product.ProductID AND Dupe.InventoryDate < GasInventory.InventoryDate ORDER BY Dupe.InventoryDate DESC) AS PreviousDayInventory, GasInventory.ActualInventory, GasInventoryTransactions.GasSales, GasInventoryTransactions.GasDelivery, [PreviousDayInventory]+[GasDelivery]-[GasSales] AS BookBalance, GasInventory.ActualInventory, [ActualInventory]-[BookBalance] AS OverShort
FROM (Stations INNER JOIN (Product INNER JOIN GasInventory ON Product.[ProductID] = GasInventory.[ProductID]) ON Stations.[StationID] = GasInventory.[StationID]) INNER JOIN GasInventoryTransactions ON GasInventory.[InventoryDate] = GasInventoryTransactions.[TransactionDate];
thanks for your help!

SQL joining tables issue

So I am trying to run a statement in SSMS like:
SELECT Project.PROJNAME FROM PROJECT
JOIN SHIPMENT ON SHIPMENT.SNUM = SUPPLIERS.SNUM
JOIN PARTS ON PARTS.PNUM = SHIPMENT.PNUM
JOIN SUPPLIERS ON PROJECT.PROJNUM = SHIPMENT.PROJNUM
WHERE SUPPLIERS.SNAME='S1' AND SUPPLIERS.SNAME='S2'
However, when I do, I have an issue with the suppliers.snum portion on line 2 of the query. It tells me the multi-part identifier cannot be bound. I have looked at several ways to rectify the problem, but for some reason its just not sinking in for the understanding on the how and why. Could someone please explain how to fix this and why exactly the current way does not work? Thanks guys, cheers.
your query looks very strange for me, try this version with proper order:
SELECT Project.PROJNAME
FROM
PROJECT
JOIN
SHIPMENT
ON PROJECT.PROJNUM = SHIPMENT.PROJNUM
JOIN
PARTS
ON SHIPMENT.PNUM = PARTS.PNUM
JOIN
SUPPLIERS
ON SHIPMENT.SNUM = SUPPLIERS.SNUM
WHERE
SUPPLIERS.SNAME IN ('S1', 'S2')

Sales report by state in magento in 1.7.0.2

There was a solution provided for 1.4 MySQL query for "Sales Report by Country and State/Province" unfortunately the table structure has changed. Anyone know a query to order sales by state in 1.7.0.2? I would be most appreciative.
Here is what i came up with:
SELECT
sales_flat_order_address.region
, count(*)
FROM
`sales_flat_order` AS `main_table` INNER JOIN `sales_flat_order_address`
ON main_table.entity_id = sales_flat_order_address.parent_id
AND sales_flat_order_address.address_type="shipping"
GROUP BY
sales_flat_order_address.region

SUM(a*b) not working

I have a PHP page running in postgres. I have 3 tables - workorders, wo_parts and part2vendor. I am trying to multiply 2 table column row datas together, ie wo_parts has a field called qty and part2vendor has a field called cost. These 2 are joined by wo_parts.pn and part2vendor.pn. I have created a query like this:
$scoreCostQuery = "SELECT SUM(part2vendor.cost*wo_parts.qty) as total_score
FROM part2vendor
INNER JOIN wo_parts
ON (wo_parts.pn=part2vendor.pn)
WHERE workorder=$workorder";
But if I add the costs of the parts multiplied by the qauntities supplied, it adds to a different number than what the script is doing. Help....I am new to this but if someone can show me in SQL I can modify it for postgres. Thanks
Without seeing example data, there's no way for us to know why you're query totals are coming out differently that when you do the math by hand. It could be a bad join, so you are getting more/less records than you expected. It's also possible that your calculations are off. Pick an example with the smallest number of associated records & compare.
My suggestion is to add a GROUP BY to the query:
SELECT SUM(p.cost * wp.qty) as total_score
FROM part2vendor p
JOIN wo_parts wp ON wp.pn = p.pn
WHERE workorder = $workorder
GROUP BY workorder
FYI: MySQL was designed to allow flexibility in the GROUP BY, while no other db I've used does - it's a source of numerous questions on SO "why does this work in MySQL when it doesn't work on db x...".
To Check that your Quantities are correct:
SELECT wp.qty,
p.cost
FROM WO_PARTS wp
JOIN PART2VENDOR p ON p.pn = wp.pn
WHERE p.workorder = $workorder
Check that the numbers are correct for a given order.
You could try a sub-query instead.
(Note, I don't have a Postgres installation to test this on so consider this more like pseudo code than a working example... It does work in MySQL tho)
SELECT
SUM(p.`score`) AS 'total_score'
FROM part2vendor AS p2v
INNER JOIN (
SELECT pn, cost * qty AS `score`
FROM wo_parts
) AS p
ON p.pn = p2v.pn
WHERE p2n.workorder=$workorder"
In the question, you say the cost column is in part2vendor, but in the query you reference wo_parts.cost. If the wo_parts table has its own cost column, that's the source of the problem.