Subqueries in Doctrine for Having field - mysql

I am dealing with several bus routes.
I want to fetch the two points closest to my departure and destination points.
So what I do is :
$q = Doctrine_query::create()
->select('r.*')
//d1 and d2 are the distance between the p1 and p2 points and my dest and depa points.
->addSelect("(6371 * ACOS(SIN(RADIANS($depa_lat)) * SIN(RADIANS(p1.lat)) + COS(RADIANS($depa_lat)) * COS(RADIANS(p1.lat)) * COS(RADIANS(p1.lng) - RADIANS($depa_lng)))) d1")
->addSelect("(6371 * ACOS(SIN(RADIANS($dest_lat)) * SIN(RADIANS(p2.lat)) + COS(RADIANS($dest_lat)) * COS(RADIANS(p2.lat)) * COS(RADIANS(p2.lng) - RADIANS($dest_lng)))) d2")
->from('Route r')
->innerJoin('r.Points p1')
->innerJoin('r.Points p2')
//this is just to select only the points close enough to my depa and dest point
->andWhere('p1.lat >= ?',$depa_lat - $eps_lat)
->andWhere('p1.lat <= ?',$depa_lat + $eps_lat)
->andWhere('p1.lng >= ?',$depa_lng - $eps_lng)
->andWhere('p1.lng <= ?',$depa_lng + $eps_lng)
->andWhere('p2.lat >= ?',$dest_lat - $eps_lat)
->andWhere('p2.lat <= ?',$dest_lat + $eps_lat)
->andWhere('p2.lng >= ?',$dest_lng - $eps_lng)
->andWhere('p2.lng <= ?',$dest_lng + $eps_lng)
//those subqueries are to fetch the two closest points, and they seem to be the cause of the crash
->having('d1 =
(
SELECT MIN((6371 * ACOS(SIN(RADIANS('.$depa_lat.')) * SIN(RADIANS(p3.lat)) + COS(RADIANS('.$depa_lat.')) * COS(RADIANS(p3.lat)) * COS(RADIANS(p3.lng) - RADIANS('.$depa_lng.')))))
FROM Point p3
WHERE p3.lat >= '.$depa_lat - $eps_lat.' AND p3.lat <= '.$depa_lat + $eps_lat.' AND p3.lng >= '.$depa_lng - $eps_lng.' AND p3.lng <= '.$depa_lng + $eps_lng.' AND p3.route_id = p1.route_id
)')
->having('d2 =
(
SELECT MIN((6371 * ACOS(SIN(RADIANS('.$dest_lat.')) * SIN(RADIANS(p4.lat)) + COS(RADIANS('.$dest_lat.')) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS('.$dest_lng.')))))
FROM Point p4
WHERE p4.lat >= '.$dest_lat - $eps_lat.' AND p4.lat <= '.$dest_lat + $eps_lat.' AND p4.lng >= '.$dest_lng - $eps_lng.' AND p4.lng <= '.$dest_lng + $eps_lng.' AND p4.route_id = p2.route_id
)')
->orderBy('d1+d2')
->execute();
The error is :
Doctrine_Exception
Couldn't find class p4
Is there a better way to do this ? I thought that MIN should go with GROUP BY, and I tried GROUP BY p3.id and GROUP BY p4.id, but that didn't change.
For those it could help, here's the stack trace from Symfony :
It's weird that the parseAggregateFunction() function erases the query, isn't it ?
at Doctrine_Table->initDefinition()
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Table.php line 256 ...
at Doctrine_Table->__construct('-58', object('Doctrine_Connection_Mysql'), 1)
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Connection.php line 1126 ...
at Doctrine_Connection->getTable('-58')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query.php line 1942 ...
at Doctrine_Query->loadRoot('-58', '-58')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query.php line 1740 ...
at Doctrine_Query->load('-58', )
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 89 ...
at Doctrine_Query_Having->_parseAliases('-58.3819582))))) FRO')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 70 ...
at Doctrine_Query_Having->parseAggregateFunction('-58.3819582))))) FRO')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('p4.lng) - RADIANS(-58.3819582))))) FROM')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM P')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Po')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Poi')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Poin')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 W')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('RADIANS(-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 WH')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('SIN(RADIANS(-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 WHE')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('6371 * ACOS(SIN(RADIANS(-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 WHER')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('(6371 * ACOS(SIN(RADIANS(-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 WHERE')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 63 ...
at Doctrine_Query_Having->parseAggregateFunction('SELECT MIN((6371 * ACOS(SIN(RADIANS(-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 WHERE 0')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Having.php line 118 ...
at Doctrine_Query_Having->load('d2 = SELECT MIN((6371 * ACOS(SIN(RADIANS(-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 WHERE 0')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Condition.php line 92 ...
at Doctrine_Query_Condition->parse('d2 = SELECT MIN((6371 * ACOS(SIN(RADIANS(-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 WHERE 0')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Condition.php line 80 ...
at Doctrine_Query_Condition->parse('d2 = SELECT MIN((6371 * ACOS(SIN(RADIANS(-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 WHERE 0 AND p4.route_id = p2.route_id')
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Abstract.php line 2077 ...
at Doctrine_Query_Abstract->_processDqlQueryPart('having', array('d2 = SELECT MIN((6371 * ACOS(SIN(RADIANS(-58.3819582)) * SIN(RADIANS(p4.lat)) + COS(RADIANS(-58.3819582)) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS(-58.3819582))))) FROM Point p4 WHERE 0 AND p4.route_id = p2.route_id'))
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query.php line 1167 ...
at Doctrine_Query->buildSqlQuery(1)
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query.php line 1133 ...
at Doctrine_Query->getSqlQuery(array())
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Abstract.php line 958 ...
at Doctrine_Query_Abstract->_execute(array())
in SF_SYMFONY_LIB_DIR/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Query/Abstract.php line 1026 ...
at Doctrine_Query_Abstract->execute()
in SF_ROOT_DIR/lib/model/doctrine/LineTable.class.php line 58 ...
at LineTable->findLinesFromLatLngToLatLng('-34.5835397', '-58.4246329', '-58.3819582', '-58.3819582', 0.4)
in SF_ROOT_DIR/apps/frontend/modules/map/actions/actions.class.php line 57 ...
at mapActions->executeSearch(object('sfWebRequest'))
in SF_SYMFONY_LIB_DIR/action/sfActions.class.php line 60 ...
at sfActions->execute(object('sfWebRequest'))
in SF_SYMFONY_LIB_DIR/filter/sfExecutionFilter.class.php line 92 ...
at sfExecutionFilter->executeAction(object('mapActions'))
in SF_SYMFONY_LIB_DIR/filter/sfExecutionFilter.class.php line 78 ...
at sfExecutionFilter->handleAction(object('sfFilterChain'), object('mapActions'))
in SF_SYMFONY_LIB_DIR/filter/sfExecutionFilter.class.php line 42 ...
at sfExecutionFilter->execute(object('sfFilterChain'))
in SF_SYMFONY_LIB_DIR/filter/sfFilterChain.class.php line 53 ...
at sfFilterChain->execute()
in SF_SYMFONY_LIB_DIR/filter/sfRenderingFilter.class.php line 33 ...
at sfRenderingFilter->execute(object('sfFilterChain'))
in SF_SYMFONY_LIB_DIR/filter/sfFilterChain.class.php line 53 ...
at sfFilterChain->execute()
in SF_SYMFONY_LIB_DIR/controller/sfController.class.php line 238 ...
at sfController->forward('map', 'search')
in SF_SYMFONY_LIB_DIR/controller/sfFrontWebController.class.php line 48 ...
at sfFrontWebController->dispatch()
in SF_SYMFONY_LIB_DIR/util/sfContext.class.php line 170 ...
at sfContext->dispatch()
in SF_ROOT_DIR/web/frontend_dev.php line 13 ...

You might try something like this:
$q = Doctrine_Query::create()
->select('r.*')
->addSelect("(6371 * ACOS(SIN(RADIANS($depa_lat)) * SIN(RADIANS(p1.lat)) + COS(RADIANS($depa_lat)) * COS(RADIANS(p1.lat)) * COS(RADIANS(p1.lng) - RADIANS($depa_lng)))) d1")
->addSelect("(6371 * ACOS(SIN(RADIANS($dest_lat)) * SIN(RADIANS(p2.lat)) + COS(RADIANS($dest_lat)) * COS(RADIANS(p2.lat)) * COS(RADIANS(p2.lng) - RADIANS($dest_lng)))) d2")
->from('Route r')
->innerJoin('r.Points p1')
->innerJoin('r.Points p2')
->andWhere('p1.lat >= ?',$depa_lat - $eps_lat)
->andWhere('p1.lat <= ?',$depa_lat + $eps_lat)
->andWhere('p1.lng >= ?',$depa_lng - $eps_lng)
->andWhere('p1.lng <= ?',$depa_lng + $eps_lng)
->andWhere('p2.lat >= ?',$dest_lat - $eps_lat)
->andWhere('p2.lat <= ?',$dest_lat + $eps_lat)
->andWhere('p2.lng >= ?',$dest_lng - $eps_lng)
->andWhere('p2.lng <= ?',$dest_lng + $eps_lng);
$d1 = $q->createSubquery()
->select('MIN((6371 * ACOS(SIN(RADIANS('.$depa_lat.')) * SIN(RADIANS(p3.lat)) + COS(RADIANS('.$depa_lat.')) * COS(RADIANS(p3.lat)) * COS(RADIANS(p3.lng) - RADIANS('.$depa_lng.')))))')
->from('Point p3')
->where('WHERE p3.lat >= '.$depa_lat - $eps_lat.' AND p3.lat <= '.$depa_lat + $eps_lat.' AND p3.lng >= '.$depa_lng - $eps_lng.' AND p3.lng <= '.$depa_lng + $eps_lng.' AND p3.route_id = p1.route_id');
$d2 = $q->createSubquery()
->select('MIN((6371 * ACOS(SIN(RADIANS('.$dest_lat.')) * SIN(RADIANS(p4.lat)) + COS(RADIANS('.$dest_lat.')) * COS(RADIANS(p4.lat)) * COS(RADIANS(p4.lng) - RADIANS('.$dest_lng.')))))')
->from('Point p4')
->where('p4.lat >= '.$dest_lat - $eps_lat.' AND p4.lat <= '.$dest_lat + $eps_lat.' AND p4.lng >= '.$dest_lng - $eps_lng.' AND p4.lng <= '.$dest_lng + $eps_lng.' AND p4.route_id = p2.route_id');
$q->having('d1 = (' . $d1->getDql() . ')')
->having('d2 = (' . $d2->getDql() . ')')
->orderBy('d1+d2')
->execute();

Related

SQL select calculations

Below are the things I'm using
lahman's baseball -database
2015 SQL version of the database.
Microsoft SQL server management studio v17.7
I'm using "Los Angeles Dodgers" statistics and I'm basing my selects of
the website and pulling from the above database Website for ESPN Los Angeles Dodgers
I'm trying to recreate the website with 7 individual select statements. I'm having issues with my second select statements at the moment, The purpose of the second is to provide a totals row at the bottom like they do on the website.
( So my main question is can someone help with fixing my second select.)
( My second question can i get some assistance on creating 5 other
selects statements that correspond with the image below.)
(1st)
Main Body Select :
SELECT
nameFirst + ' ' + nameLast AS Name,
G AS GP,
AB,
R,
H,
H - B2 - B3 - HR AS S,
B2 AS '2B',
B3 AS '3B',
HR,
RBI,
(((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4)) AS 'TB',
BB,
SO,
SB,
(H * 1.0) / (CASE
WHEN AB = 0 THEN 1
ELSE AB
END) AS 'BA',
(CASE
WHEN (H + BB + HBP) = 0 THEN 0
ELSE ((H + BB + HBP) * 1.0)
END) / (CASE
WHEN (AB + BB + HBP) = 0 THEN 1.0
ELSE ((AB + BB + HBP) * 1.0)
END) AS 'OBP',
(CASE
WHEN (((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4)) = 0 THEN 0
ELSE (((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4))
END) / (CASE
WHEN AB = 0 THEN 1
ELSE AB
END) AS 'SLG',
(CASE
WHEN (H + BB + HBP) = 0 THEN 0
ELSE ((H + BB + HBP) * 1.0)
END) / (CASE
WHEN (AB + BB + HBP) = 0 THEN 1.0
ELSE ((AB + BB + HBP) * 1.0)
END) +
(CASE
WHEN (((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4)) = 0 THEN 0
ELSE (((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4))
END) / (CASE
WHEN AB = 0 THEN 1
ELSE AB
END) AS 'OPS'
FROM Players
LEFT OUTER JOIN Batting
ON Players.playerIDpk = Batting.playerID
WHERE teamID = 'LAN'
AND yearID = '2012'
ORDER BY BA DESC
Click Here - For Image of above select output
(2nd)
Total Select:
SELECT
'' AS Total,
'162' AS 'GP',
SUM(AB) AS 'AB',
SUM(R) AS 'R',
SUM(H) AS 'H',
SUM(B2) AS '2B',
SUM(B3) AS '3B',
SUM(HR) AS HR,
SUM(RBI) AS RBI,
SUM((((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4))) AS 'TB',
SUM(BB) AS BB,
SUM(SO) AS 'SO',
SUM(SB) AS 'SB',
AVG((H * 1.0) / (CASE
WHEN AB = 0 THEN 1
ELSE AB
END)) AS 'BA',
AVG((CASE
WHEN (H + BB + HBP) = 0 THEN 0
ELSE ((H + BB + HBP) * 1.0)
END) / (CASE
WHEN (AB + BB + HBP) = 0 THEN 1.0
ELSE ((AB + BB + HBP) * 1.0)
END)) AS 'OBP',
AVG((CASE
WHEN (((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4)) = 0 THEN 0
ELSE (((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4))
END) / (CASE
WHEN AB = 0 THEN 1
ELSE AB
END)) AS 'SLG',
AVG((CASE
WHEN (((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4)) = 0 THEN 0
ELSE (((H - B2 - B3 - HR) * 1.0) + (B2 * 2) + (B3 * 3) + (HR * 4))
END) / (CASE
WHEN AB = 0 THEN 1
ELSE AB
END)) AS 'OPS'
FROM Players
LEFT OUTER JOIN Batting
ON Players.playerIDpk = Batting.playerID
WHERE teamID = 'LAN'
AND yearID = '2012'
Here's what my total select returns and its incorrect.
Below is what it should return when i run the select for totals i don't know what i did wrong.
Looking at only the total value for the column BA it is clear that you are not doing the same calculations as them, instead of calculating average values you should calculate the ratio betweens the sum of the columns H and AB
So replace
AVG((H * 1.0) / (CASE
WHEN AB = 0 THEN 1
ELSE AB
END)) AS 'BA',
with
SUM(H) / SUM(AB) AS 'BA'
I haven't checked the other incorrect columns but I assume it's the same issue.

mysql query takes too long

im working on a project and I created this sql query but it seems to be taking too long if I select a bigger date range, any idea how to make it faster, I tryed with union all and its much faster, but data is not the same, need help with code:
SELECT SUM(ROUND(total, 2)) as Enero from (
SELECT
FORMAT (
COALESCE(
CONCAT(ROUND(pro.precio / 1.14 , 2) + ROUND(p.recargo / 1.14 , 2) + (SELECT SUM(ROUND(precio / 1.14 , 2)) AS precio FROM acompanante_orden WHERE id_orden=p.id_orden) - p.descuento),
CONCAT(ROUND(pro.precio / 1.14 , 2) + ROUND(p.recargo / 1.14 , 2) - p.descuento)
)+ COALESCE(
ROUND(CONCAT(ROUND(pro.precio / 1.14 , 2) + (SELECT SUM(ROUND(precio / 1.14 , 2)) AS precio FROM acompanante_orden WHERE id_orden=p.id_orden) + ROUND(p.recargo / 1.14 , 2) - p.descuento) * 0.14, 2),
ROUND(CONCAT(ROUND(pro.precio / 1.14 , 2) + ROUND(p.recargo / 1.14 , 2) - p.descuento) * 0.14, 2)
), 2) as total
FROM orden p
LEFT JOIN producto_orden AS pro ON p.id_orden = pro.id_orden
LEFT JOIN acompanante_orden AS pa ON p.id_orden = pa.id_orden
WHERE p.actual_date BETWEEN '2017-04-01' AND '2017-04-01' and p.status=4
) sum_1
UNION ALL IDEA
select ROUND(( sum(precio)) * 1.14,2) as total from (
SELECT a.id_orden, ROUND(b.precio / 1.14 , 2) + ROUND(a.recargo / 1.14 , 2) - a.descuento as precio FROM orden a, producto_orden b WHERE a.id_orden=b.id_orden and a.actual_date BETWEEN '2017-04-01' AND '2017-04-01' and a.status=4 union all
SELECT c.id_orden, ROUND(d.precio / 1.14 , 2) as precio FROM orden c, acompanante_orden d WHERE c.id_orden=d.id_orden and c.actual_date BETWEEN '2017-04-01' AND '2017-04-01' and c.status=4
) sum_1
UPDATE:
SO here is my table schema: http://sqlfiddle.com/#!9/4fe12/2
WHAT I NEED:
I need to get TOTAL of monthly SELLS, but values on DB are with TAXES so before I get total I need to do some math:
DB INFO
PRODUCT= $50.00
ADDONS= $8.00
SHIPPING= $6.00
DISCOUNT= $2.00
RESULTS I NEED:
PRODUCT= $50.00 / 1.14 = $43.86
ADDONS= $8.00 / 1.14 = $7.02
SHIPPING= $6.00 / 1.14 =$5.26
SUBTOTAL= $56.14 - DISCOUNT($2)= $54.14
SUBTOTAL= $54.14 * 1.14 = $61.72
The first subquery is basically:
SELECT . . .
FROM orden p LEFT JOIN
producto_orden pro
ON p.id_orden = pro.id_orden LEFT JOIN
acompanante_orden pa
ON p.id_orden = pa.id_orden
WHERE p.actual_date BETWEEN '2017-04-01' AND '2017-04-01' and
p.status = 4
For this query, you want indexes on orden(status, actual_date, id_id_orden), producto_orden(id_orden), andacompanante_orden(id_orden)`.
I'm not sure what the rest of the query is.

mysql matching multiple and's and or's

I am trying to get rows from a table where there are matches on multiple other tables.
This is the query I am running.
SELECT qt.*, DATEDIFF(CURRENT_DATE, STR_TO_DATE(up.DOB, '%m-%d-%Y')) / 365 AS Age
FROM UserProfile AS up, Game AS g, QuestionTable AS qt
WHERE NOT EXISTS(SELECT * FROM Options WHERE UserID = 75 AND QID = qt.QID AND DateTime >= CURDATE())
AND g.Active = 1 AND g.QID = qt.QID
AND (((g.Gender = up.Gender OR g.Gender = 'B') AND ((g.City = up.City AND g.Zip = up.Zip AND g.Country = up.Country) OR g.Home = 0) AND ((Age BETWEEN g.Maximum AND g.Minimum) OR g.Age = 0) AND ((SQRT( POW( 69.1 * ( g.Latitude - -93.5746359 ) , 2 ) + POW( 69.1 * ( 44.9737707 - g.Longitude ) * COS( g.Latitude / 57.3 ) , 2 ) ) > g.Distance) OR g.Geo = 0)) OR g.Special = 0)
GROUP BY qt.QID
I have ran this expression through C# and it returns true, yet it is only matching on the 'g.Special = 0' part through MySql.
Any help on this would be much appreciated!
Resolved the issue by fixing some mistakes I made and changed the query to this,
SELECT *
FROM QuestionTable AS qt
WHERE NOT EXISTS
(SELECT * FROM Options WHERE UserID = 75 AND QID = qt.QID AND DateTime >= CURDATE())
AND EXISTS(SELECT g.* FROM UserProfile AS up, Game AS g WHERE g.Active = 1 AND g.QID = qt.QID AND(g.Special = 0 OR(
(g.Gender = up.Gender OR g.Gender = 'B') AND
((g.City = up.City AND g.zip = up.Zip AND g.Country = up.Country) OR g.Home = 0) AND
((SQRT( POW( 69.1 * ( g.Latitude - 44.9737707 ) , 2 ) + POW( 69.1 * ( -93.5746359 - g.Longitude ) * COS( g.Latitude / 57.3 ) , 2 ) ) < g.Distance) OR g.Geo = 0) AND
((DATEDIFF(CURRENT_DATE, STR_TO_DATE(DOB, '%m/%d/%Y'))/365.25 BETWEEN g.Minimum AND g.Maximum) OR g.Age = 0))))

SUM from two tables, sort by country and publisher

I have two different sales tables and i want to SUM the quantity and FEEs for storeX and storeY from book_sales(isa), with quantity from all sales in the financial_report(xo). Im having trouble with both, and i dont know which JOIN i should use. The quantity calculation does not give any results and the fee calculation gives a number that is way to high. What is wrong here?
Please check my procedure if you have time:
ALTER PROCEDURE [dbo].[Report] #startDate VARCHAR(10),
#endDate VARCHAR(10)
AS
SELECT BB.name AS 'Publisher',
Sum(CASE
WHEN isa.report_source = 'storeX'
or isa.report_source = 'storeY' THEN
isa.quantity * xo.quantity
END) AS 'Total quantity',
Sum(CASE
WHEN isa.sales_price > 69
AND isa.report_source = 'storeX' THEN
6 * 1.25 * isa.quantity
WHEN isa.sales_price <= 69
AND isa.report_source = 'storeX' THEN
3 * 1.25 * isa.quantity
WHEN isa.sales_price <= 19
AND isa.report_source = 'storeX' THEN
1 * 1.25 * isa.quantity
WHEN isa.sales_price > 69
AND isa.report_source = 'storeY' THEN
6 * 1.25 * isa.quantity
WHEN isa.sales_price <= 69
AND isa.report_source = 'storeY' THEN
3 * 1.25 * isa.quantity
WHEN isa.sales_price <= 19
AND isa.report_source = 'storeY' THEN
1 * 1.25 * isa.quantity
WHEN xo.sales_price > 69
AND bb.country = 'NOR' THEN 6 * 1.25 * xo.quantity
WHEN xo.sales_price <= 69
AND bb.country = 'NOR' THEN 3 * 1.25 * xo.quantity
WHEN xo.sales_price > 69
AND bb.country <> 'NOR' THEN 6 * xo.quantity
WHEN xo.sales_price <= 69
AND bb.country <> 'NOR' THEN 3 * xo.quantity
END) AS 'Fee inc VAT(tot)'
FROM book_sales AS isa
INNER JOIN store AS BV
ON bv.store_id = isa.store_id
INNER JOIN financial_report AS xo
ON xo.identifiers = isa.identifiers
LEFT OUTER JOIN publisher AS BB
ON bb.publisher_id = bk.publisher_id
WHERE isa.sales_date >= CONVERT(DATETIME, #startDate, 20)
AND isa.sales_date < Dateadd(day, 1, ( CONVERT(DATETIME, #endDate, 20
) ))
GROUP BY bb.name,
bb.country
There are a few problems to sort out :
1- The total might be affected by NULL values, I suggest:
Sum(CASE
WHEN isa.report_source = 'storeX'
or isa.report_source = 'storeY' THEN
isnull(isa.quantity,0) * isnull(xo.quantity,0)
ELSE 0 END) AS 'Total quantity',
2- The case evaluation should be in order. For example:
WHEN isa.sales_price <= 69
AND isa.report_source = 'storeX' THEN
3 * 1.25 * isa.quantity
WHEN isa.sales_price <= 19
AND isa.report_source = 'storeX' THEN
1 * 1.25 * isa.quantity
<= 19 will never happen because it is also <= 69 and therefore the <=69 will evaluate true.
3- Cardinality between tables might be 1 to many so the values are summed multiple times when they shouldn't. You may need to select distinct or aggregate or flatten out some of the tables in the join to avoid this issue.

SQL SUM Query with subqueries

I am trying to get the total 'capacity' for each station but I keep getting the error message "#1630 - FUNCTION tflBikes.COUNT does not exist":
SELECT Count(ts.capacity),
tbu.stationid,
ts.name,
ts.easting,
ts.northing,
tbu.t,
Round(Avg(availablebikes), 1) AS Average,
Round(Avg(availablebikes) / capacity * 100, 1) AS Percentage,
ts.postcode
FROM tflbikeusage tbu,
tflstations ts
WHERE tbu.stationid = ts.usageid
AND ts.easting = Abs(easting -
(SELECT easting
FROM tflstations
WHERE name = 'Hatton Garden, Holborn')) < 750 * 0.5
AND ts.northing = Abs(northing -
(SELECT northing
FROM tflstations
WHERE name = 'Hatton Garden, Holborn')) < 750 * 0.5
AND Hour(t) BETWEEN 10 AND 22
GROUP BY ts.capacity HAVING COUNT (ts.capacity) =
(SELECT Sum(capacityno)
FROM
(SELECT COUNT(ts.capacity) AS capacityNo,
tbu.stationid,
ts.name,
ts.easting,
ts.northing,
tbu.t,
Round(Avg(availablebikes), 1) AS Average,
Round(Avg(availablebikes) / capacity * 100 , 1) AS Percentage,
ts.postcode
FROM tflbikeusage tbu,
tflstations ts
WHERE tbu.stationid = ts.usageid
AND ts.easting = Abs(easting -
(SELECT easting
FROM tflstations
WHERE name = 'Hatton Garden, Holborn')) < 750 * 0.5
AND ts.northing = Abs(northing -
(SELECT northing
FROM tflstations
WHERE name = 'Hatton Garden, Holborn')) < 750 * 0.5
AND Hour(t) BETWEEN 10 AND 22
GROUP BY ts.capacity
ORDER BY percentage DESC)derivedTable)
You are aliasing tflbikesUsage to "tbu", so you should be using that going forward.