Probably subquerys and not joins - sql

This big query below returns me 2860 records and its correct number. I'm getting. The thing is that I need to add to this query invoice lines and make the same thing as I did with sale_order_lines "sum(l.price_subtotal / COALESCE(cr.rate, 1.0)) AS price_subtotal". I need to get the sum of price_subtotal of invoice lines.
so my first thought was to join tables like this.
JOIN sale_order_invoice_rel so_inv_rel on (so_inv_rel.order_id = s.id )
JOIN account_invoice inv on (inv.id = so_inv_rel.invoice_id and inv.state in ('open','paid'))
JOIN account_invoice_line ail on (inv.id = ail.invoice_id)
and then
sum(ail.price_subtotal / COALESCE(cr.rate, 1.0)) as price_subtotal
but after the first JOIN number of lines, I'm selecting is changing and even if I joins are done the numbers are way off basically I get 5x2860. So probably I need to make some subquery but at this point, I don't know how and asking for help.
WITH currency_rate AS (
SELECT r.currency_id,
COALESCE(r.company_id, c.id) AS company_id,
r.rate,
r.name AS date_start,
( SELECT r2.name
FROM res_currency_rate r2
WHERE r2.name > r.name AND r2.currency_id = r.currency_id AND (r2.company_id IS NULL OR r2.company_id = c.id)
ORDER BY r2.name
LIMIT 1) AS date_end
FROM res_currency_rate r
JOIN res_company c ON r.company_id IS NULL OR r.company_id = c.id
)
SELECT min(l.id) AS id,
l.product_id,
l.color_id,
l.product_size_id,
t.uom_id AS product_uom,
sum(l.product_uom_qty / u.factor * u2.factor) AS product_uom_qty,
sum(l.qty_delivered / u.factor * u2.factor) AS qty_delivered,
sum(l.qty_invoiced / u.factor * u2.factor) AS qty_invoiced,
sum(l.qty_to_invoice / u.factor * u2.factor) AS qty_to_invoice,
sum(l.price_total / COALESCE(cr.rate, 1.0)) AS price_total,
l.price_unit / COALESCE(cr3.rate, 1.0) AS price_total_by_cmp_curr,
sum(l.price_subtotal / COALESCE(cr.rate, 1.0)) AS price_subtotal,
count(*) AS nbr,
s.date_order AS date,
s.state,
s.partner_id,
s.user_id,
s.company_id,
date_part('epoch'::text, avg(date_trunc('day'::text, s.date_order) - date_trunc('day'::text, s.create_date))) / (24 * 60 * 60)::numeric(16,2)::double precision AS delay,
t.categ_id,
s.pricelist_id,
s.project_id AS analytic_account_id,
s.team_id,
p.product_tmpl_id,
partner.country_id,
partner.commercial_partner_id
FROM sale_order_line l
JOIN sale_order s ON l.order_id = s.id
JOIN res_partner partner ON s.partner_id = partner.id
LEFT JOIN product_product p ON l.product_id = p.id
LEFT JOIN product_template t ON p.product_tmpl_id = t.id
LEFT JOIN product_uom u ON u.id = l.product_uom
LEFT JOIN product_uom u2 ON u2.id = t.uom_id
LEFT JOIN res_company rc ON rc.id = s.company_id
LEFT JOIN product_pricelist pp ON s.pricelist_id = pp.id
LEFT JOIN currency_rate cr ON cr.currency_id = pp.currency_id AND cr.company_id = s.company_id AND cr.date_start <= COALESCE(s.date_order::timestamp with time zone, now()) AND (cr.date_end IS NULL OR cr.date_end > COALESCE(s.date_order::timestamp with time zone, now()))
LEFT JOIN currency_rate cr3 ON cr.currency_id = rc.currency_id AND cr.company_id = s.company_id AND cr.date_start <= COALESCE(s.date_order::timestamp with time zone, now()) AND (cr.date_end IS NULL OR cr.date_end > COALESCE(s.date_order::timestamp with time zone, now()))
GROUP BY l.product_id, t.uom_id, t.categ_id, s.date_order, s.partner_id, s.user_id, s.state, s.company_id, s.pricelist_id, s.project_id, s.team_id, l.color_id, cr3.rate, l.price_unit, l.product_size_id, p.product_tmpl_id, partner.country_id, partner.commercial_partner_id;

You can add the part that could be in a subquery to the with statement you already have to avoid the increase in number of lines, like so:
WITH currency_rate AS (
SELECT r.currency_id,
COALESCE(r.company_id, c.id) AS company_id,
r.rate,
r.name AS date_start,
( SELECT r2.name
FROM res_currency_rate r2
WHERE r2.name > r.name AND r2.currency_id = r.currency_id AND (r2.company_id IS NULL OR r2.company_id = c.id)
ORDER BY r2.name
LIMIT 1) AS date_end
FROM res_currency_rate r
JOIN res_company c ON r.company_id IS NULL OR r.company_id = c.id
)
, order_line_subtotal AS(
SELECT so_inv_rel.order_id, sum(ail.price_subtotal) as price_subtotal
FROM sale_order_invoice_rel so_inv_rel
JOIN account_invoice inv on (inv.id = so_inv_rel.invoice_id and inv.state in ('open','paid'))
JOIN account_invoice_line ail on (inv.id = ail.invoice_id)
GROUP BY so_inv_rel.order_id )
SELECT min(l.id) AS id,
....
From there it should be straightforward to add to the query without increasing the number of rows (since from the joins you already have a row for each order before the aggregation / group by.

Related

Error in on clause comparison - Big Query

The following big query code gives the following error.
select
selected_date date,
pp.name property,
bb.bookings bb,
av.available vailable,
from
(SELECT DATE(DATE_ADD(TIMESTAMP("2017-10-01"), pos - 1, "DAY")) AS selected_date
FROM (
SELECT ROW_NUMBER() OVER() AS pos, *
FROM (FLATTEN((
SELECT SPLIT(RPAD('', 1 + DATEDIFF(TIMESTAMP(CURRENT_DATE()), TIMESTAMP("2017-10-01")), '.'),'') AS h
FROM (SELECT NULL)),h
)))) v
cross join
(select p.name name from [roomsproperties.properties] p where p.name not like '%test%' group by name) as pp
left join
(select sum(b.rooms) bookings,
p.name property,
b.checkin checkin,
b.checkout checkout
from [bookings.bookings] b
left join [roomsproperties.rooms] r on r.id = b.room_id
left join [roomsproperties.properties] p on p.id = r.property_id
where p.name not like '%test%'
and b.status not in('Rejected', 'Cancelled - By customer', 'OTP Not Varified')
group by property,checkin,checkout
) as bb on pp.name = bb.property and (v.selected_date between bb.checkin and bb.checkout)
left join
(select sum(r.quantity) available,
p.name property,
date(r.created_at) date
from [roomsproperties.rooms] r
left join [roomsproperties.properties] p on p.id = r.property_id
group by property, date
) av on pp.name = av.property and v.selected_date >= av.date
The error is,
Error: ON clause must be AND of = comparisons of one field name from each table, with all field names prefixed with table name. Consider using Standard SQL
Can any one help
You should try:
(select ...) as bb on pp.name = bb.property
WHERE v.selected_date between bb.checkin and bb.checkou
and:
(select ...) as av on pp.name = av.property
WHERE v.selected_date >= av.date

I am getting a syntax error on this SQL script when trying to pull data via an ODBC and i'm not sure how/why

I am running the following script but am encountering an error. It is essentially the combination of two separate scripts. So I think one of the JOINs is off but not sure where. I am pulling data from our ERP via an ODBC in winsql.
Also how would I add month to this? Probably something simple like:
TO_CHAR(Month(t.TRANDATE,'YYYY-MM-DD')) AS CreatedMonth
The query which has got problem is:
SELECT
t.TRANSACTION_TYPE AS TranType
,tl.ACCOUNT_ID AS AcctId
,a.NAME AS Account
,a.TYPE_NAME AS AcctType
,t.TRANSACTION_ID AS DCOGSTranId
,t.TRANID AS DCOGSNo
,TO_CHAR(t.TRANDATE,'YYYY-MM-DD') AS DCOGSCreateDt
,TO_CHAR(t.TRANDATE,'YYYY-MM-DD') AS CDate
,t.CREATED_BY_ID AS DCOGSCreatedById
,tl.SUBSIDIARY_ID AS SubSidId
,ss.NAME AS SubSidiary
,tl.LOCATION_ID AS LocId
,t.ENTITY_ID AS CustomerId
,tl.ITEM_ID AS ItemId
,NVL(SUM(tl.GROSS_AMOUNT),0) AS DirectCOGS$
,NVL(SUM(tl.ITEM_COUNT),0) AS DirectCOGSQty
,ilm.ITEM_ID AS ItemId
,ss.NAME AS SubSidiary
,ilm.LOCATION_ID AS LocId
,TO_CHAR(ed.ExpireDt,'YYYY-MM-DD') AS ExpireDt
,TO_CHAR(CURRENT_DATE,'YYYY-MM-DD') AS CDate
,NVL(ilm.AVERAGE_COST,0)*NVL(u.CONVERSION_RATE,1) AS AvgCost
,NVL(ilm.LAST_PURCHASE_PRICE,0)*NVL(u.CONVERSION_RATE,1) AS LastPurchPrice
,NVL(ilm.AVERAGE_COST,0) * NVL(ilm.ON_HAND_COUNT,0) AS OnHandCost$
,NVL(ilm.ON_HAND_COUNT,0) / NVL(u.CONVERSION_RATE,1) AS OnHandQty
,NVL(bin.BinOnHandQty,0) / NVL(u.CONVERSION_RATE,1) AS BinOnHandQty
,NVL(ilm.AVERAGE_COST,0) * (NVL(ilm.IN_TRANSIT_COUNT,0)) AS InTranCost$
,NVL(ilm.IN_TRANSIT_COUNT,0) / NVL(u.CONVERSION_RATE,1) AS InTranQty
,NVL(ilm.AVERAGE_COST,0) * (NVL(ilm.AVAILABLE_COUNT,0)) AS AvailCost$
,NVL(ilm.AVAILABLE_COUNT,0) / NVL(u.CONVERSION_RATE,1) AS AvailQty
,NVL(bin.BinAvailQty,0) / NVL(u.CONVERSION_RATE,1) AS BinAvailQty
,NVL(ilm.AVERAGE_COST,0) * (NVL(ilm.ON_ORDER_COUNT,0)) AS OnOrderCost$
,NVL(ilm.ON_ORDER_COUNT,0) / NVL(u.CONVERSION_RATE,1) AS OnOrderQty
,NVL(ilm.AVERAGE_COST,0) * (NVL(ilm.QUANTITYBACKORDERED,0)) AS BackOrdrdCost$
,NVL(ilm.QUANTITYBACKORDERED,0) / NVL(u.CONVERSION_RATE,1) AS BackOrdrdQty
FROM TRANSACTIONS t
JOIN TRANSACTION_LINES tl ON t.TRANSACTION_ID = tl.TRANSACTION_ID
LEFT JOIN ITEMS i ON tl.ITEM_ID = i.ITEM_ID
LEFT JOIN TRANSACTIONS t2 ON t.CREATED_FROM_ID = t2.TRANSACTION_ID
LEFT JOIN ACCOUNTS a ON tl.ACCOUNT_ID = a.ACCOUNT_ID
LEFT JOIN SUBSIDIARIES ss ON tl.SUBSIDIARY_ID = ss.SUBSIDIARY_ID
WHERE tl.ACCOUNT_ID = 128
FULL OUTER JOIN ITEM_LOCATION_MAP ilm ON tl.ITEM_ID = ilm.ITEM_ID
JOIN ITEMS i ON ilm.ITEM_ID = i.ITEM_ID
LEFT JOIN UOM u ON i.PURCHASE_UNIT_ID = u.UOM_ID
LEFT JOIN PRIMARY_SUBSIDIARYS_MAP psm ON ilm.ITEM_ID = psm.ITEM_ID
LEFT JOIN SUBSIDIARIES ss ON psm.SUBSIDIARY_ID = ss.SUBSIDIARY_ID
LEFT JOIN (
SELECT ITEM_ID, LOCATION_ID, MIN(EXPIRATION_DATE) AS ExpireDt FROM INVENTORY_NUMBER
WHERE EXPIRATION_DATE IS NOT NULL
GROUP BY ITEM_ID, LOCATION_ID) ed ON ilm.ITEM_ID = ed.ITEM_ID AND
ilm.LOCATION_ID = ed.LOCATION_ID
LEFT JOIN (
SELECT ITEM_ID, LOCATION_ID, SUM(ON_HAND_COUNT) AS BinOnHandQty,
SUM(AVAILABLE_COUNT) AS BinAvailQty
FROM BIN_NUMBER_COUNTS
GROUP BY ITEM_ID, LOCATION_ID) bin ON ilm.ITEM_ID = bin.ITEM_ID AND
ilm.LOCATION_ID = bin.LOCATION_ID
WHERE (ilm.ON_HAND_COUNT != 0 OR ilm.IN_TRANSIT_COUNT != 0 OR
ilm.ON_ORDER_COUNT != 0 OR ilm.QUANTITYBACKORDERED != 0)
GROUP BY
t.TRANSACTION_TYPE
,tl.ACCOUNT_ID
,a.NAME
,a.TYPE_NAME
,t.TRANSACTION_ID
,t.TRANID
,t.TRANDATE
,t.CREATED_BY_ID
,tl.SUBSIDIARY_ID
,ss.NAME
,tl.LOCATION_ID
,t.ENTITY_ID
,tl.ITEM_ID
Really should post what the error is to help us out...but
LEFT JOIN SUBSIDIARIES ss ON tl.SUBSIDIARY_ID = ss.SUBSIDIARY_ID
WHERE tl.ACCOUNT_ID = 128
FULL OUTER JOIN ITEM_LOCATION_MAP ilm ON tl.ITEM_ID = ilm.ITEM_ID
Replace WHERE with AND.
where is a separate clause and not part of the join statement. you can use and key1 = key 1 and key 2 = key 2 and key 3 = 'hi'

sqlite return subquery multi column

I have a sqlite subquery with the following query which is calculating the hours and labour_rate. The only issue I now have is can I get the two columns from my subquery to output in the main query. I've tried to layout the query according to some of the web tutorials but need that little bit of help to get me over the finish line as I keep getting a syntax error
SELECT c.customerID, c.customer, sum( ifnull(il.line_price, 0 ) )/10000 AS net,
FROM customer AS c
LEFT JOIN invoice AS i
ON c.customerID = i.customerID
LEFT JOIN invoice_line AS il
ON i.invoiceID = il.invoiceID
(SELECT sum(( ifnull(tl.mon,0) + ifnull(tl.tues,0) + ifnull(tl.wed,0) + ifnull(tl.thurs,0) + ifnull(tl.fri,0) + ifnull(tl.sat,0) + ifnull(tl.sun,0) ) * s.cost_rate)/10000 AS labour_rate,
sum(( ifnull(tl.mon,0) + ifnull(tl.tues,0) + ifnull(tl.wed,0) + ifnull(tl.thurs,0) + ifnull(tl.fri,0) + ifnull(tl.sat,0) + ifnull(tl.sun,0) ))/10000 AS
FROM timesheet_line AS tl
LEFT JOIN timesheet AS t
ON tl.timesheetID = t.timesheetID
LEFT JOIN staff AS s
ON t.staffID = s.staffID
WHERE (c.customerID = tl.customerID) AND (t.date BETWEEN '2014-03-01' AND '2015-12-01')
GROUP BY tl.customerID) AS time1
WHERE (i.date BETWEEN '2014-03-01' AND '2015-12-01') AND (time1.customerID = tl.customerID)
GROUP BY c.customerID
ORDER BY c.customer ASC
There are a few syntax errors in here. The first (and possibly most important) is you have to JOIN your subquery to the rest of the result set. So after
LEFT JOIN invoice_line AS il
ON i.invoiceID = il.invoiceID
you will need to add another JOIN statement:
LEFT JOIN
(SELECT
SUM(...) AS labour_rate,
SUM(...) AS hours,
tl.customerID
FROM
...) AS time1
ON <your join condition>
You will have to select some sort of field in your sub query that you can join back to the the invoice on i.e. tl.customerID.
Also, in your subquery you cannot reference a field that is outside of it, so where you have WHERE (c.customerID = tl.customerID) in your subquery it will fail because you are trying to reference c.<fieldname>. It needs to be moved to the ON part of the JOIN clause. Once you get your JOIN working correctly then you can just change your outer-most SELECT to something like
SELECT c.customerID, c.customer, sum(ifnull(il.line_price,0))/10000 AS net, time1.labour_rate, time1.hours
Here's an example of how I would do it:
SELECT c.customerID, c.customer, sum( ifnull(il.line_price, 0 ) )/10000 AS net, time1.labour_rate, time1.[hours]
FROM customer AS c
LEFT JOIN invoice AS i
ON c.customerID = i.customerID
LEFT JOIN invoice_line AS il
ON i.invoiceID = il.invoiceID
LEFT JOIN
(SELECT
sum(( ifnull(tl.mon,0) + ifnull(tl.tues,0) + ifnull(tl.wed,0) + ifnull(tl.thurs,0) + ifnull(tl.fri,0) + ifnull(tl.sat,0) + ifnull(tl.sun,0) ) * s.cost_rate)/10000 AS labour_rate,
sum(( ifnull(tl.mon,0) + ifnull(tl.tues,0) + ifnull(tl.wed,0) + ifnull(tl.thurs,0) + ifnull(tl.fri,0) + ifnull(tl.sat,0) + ifnull(tl.sun,0) ))/10000 AS [hours],
tl.customerID
FROM timesheet_line AS tl
LEFT JOIN timesheet AS t
ON tl.timesheetID = t.timesheetID
LEFT JOIN staff AS s
ON t.staffID = s.staffID
WHERE (t.date BETWEEN '2014-03-01' AND '2015-12-01')
GROUP BY tl.customerID) AS time1
ON c.customerID = time1.customerID
WHERE (i.date BETWEEN '2014-03-01' AND '2015-12-01')
GROUP BY c.customerID
ORDER BY c.customer ASC

Using a group by to group a select statement

Using a group by to group a select stament
SELECT
k.Ivalue, k.JOBDESCRIPTION ,
count( k.Ivalue) as TOTAL
FROM
(SELECT
a."ID" as Ivalue, b."JOBDESCRIPTION", rq."CURRENTSTATUS"
FROM
tblG2o_Requests a
INNER JOIN
tblG2o_JOBS b ON a."JOBPOSTID" = b."ID"
INNER JOIN
(SELECT
r.REQUESTID, ir."CURRENTSTATUS"
FROM
TBLG2O_RESULTSPOOL r
INNER JOIN
tblG2o_Requests ir ON r.RequestID = ir."ID"
WHERE
r.ShortListed = '1') rq ON rq.REQUESTID = a."ID"
WHERE
"ACTIVE" = '1'
AND "DATECOMPLETED" IS NULL
ORDER BY
"REQUESTDATE" DESC) k
GROUP BY
k.JOBDESCRIPTION
What is the question? You seem to be missing the group by clause, and you do not need double quotes around field names unless you have spaces in them, and even then, if TSQL for example, you would use [] in preference.
I had to remove an ORDER BY in the subquery, that isn't allowed unless other conditions demand it (like TOP n in TSQL)
SELECT
k.Ivalue
, k.JOBDESCRIPTION
, COUNT(k.Ivalue) AS TOTAL
FROM (
SELECT
a.ID AS Ivalue
, b.JOBDESCRIPTION
, rq.CURRENTSTATUS
FROM tblG2o_Requests a
INNER JOIN tblG2o_JOBS b
ON a.JOBPOSTID = b.ID
INNER JOIN (
SELECT
r.REQUESTID
, ir.CURRENTSTATUS
FROM TBLG2O_RESULTSPOOL r
INNER JOIN tblG2o_Requests ir
ON r.RequestID = ir.ID
WHERE r.ShortListed = '1'
) rqenter
ON rq.REQUESTID = a.ID
WHERE ACTIVE = '1'
AND DATECOMPLETED IS NULL
) k
GROUP BY
k.Ivalue
, k.JOBDESCRIPTION
Finally worked
SELECT
k.Ivalue
, l.JOBDESCRIPTION
, k.TOTAL,
k.CURRENTSTATUS
FROM (
SELECT
a.ID AS Ivalue
,b.ID as JobPostID
, rq."CURRENTSTATUS"
,COUNT(a.ID) AS TOTAL
FROM tblG2o_Requests a
INNER JOIN tblG2o_JOBS b
ON a."JOBPOSTID" = b.ID
INNER JOIN (
SELECT
r."REQUESTID"
, ir."CURRENTSTATUS"
FROM TBLG2O_RESULTSPOOL r
INNER JOIN tblG2o_Requests ir
ON r."REQUESTID" = ir.ID
WHERE r."SHORTLISTED" = 1
) rq
ON rq."REQUESTID" = a.ID
WHERE ACTIVE = '1'
AND DATECOMPLETED IS NULL
GROUP BY
a.ID ,b.ID
, rq."CURRENTSTATUS" ) k
inner join tblG2o_JOBS l on k.JobPostID =l.ID
enter code here

SQL query too big - Can I merge this?

I have the query below which seems to work, but it really feels like I should be able to do it in a simpler manner. Basically I have an orders table and a production_work table. I want to find all orders which are not complete, meaning either there's no entry for the order in the production_work table, or there are entries and the sum of the work equals what the order calls for.
SELECT q.* FROM (
SELECT o.ident, c."name" AS cname, s."name" as sname, o.number, o.created, o.due, o.name, o.ud, o.dp, o.swrv, o.sh, o.jmsw, o.sw, o.prrv, o.mhsw, o.bmsw, o.mp, o.pr, o.st
FROM orders o
INNER JOIN stations s on s.ident = o.station_id
INNER JOIN clients c ON s.client_id = c.ident
INNER JOIN (
SELECT p.order_id, SUM(p.ud) AS ud, SUM(p.dp) AS dp, SUM(p.swrv) AS swrv, SUM(p.sh) AS sh, SUM(p.jmsw) AS jmsw, SUM(p.sw) AS sw, SUM(p.prrv) AS prrv,
SUM(p.mhsw) AS mhsw, SUM(p.bmsw) AS bmsw, SUM(p.mp) AS mp, SUM(p.pr) AS pr, SUM(p.st) AS st
FROM production_work p
GROUP BY p.order_id
) pw ON o.ident = pw.order_id
WHERE o.ud <> pw.ud OR o.dp <> pw.dp OR o.swrv <> pw.swrv OR o.sh <> pw.sh OR o.jmsw <> pw.jmsw OR o.sw <> pw.sw OR o.prrv <> pw.prrv OR
o.mhsw <> pw.mhsw OR o.bmsw <> pw.bmsw OR o.mp <> pw.mp OR o.pr <> pw.pr OR o.st <> pw.st
UNION
SELECT o.ident, c."name" AS cname, s."name" as sname, o.number, o.created, o.due, o.name, o.ud, o.dp, o.swrv, o.sh, o.jmsw, o.sw, o.prrv, o.mhsw, o.bmsw, o.mp, o.pr, o.st
FROM orders o
INNER JOIN stations s on s.ident = o.station_id
INNER JOIN clients c ON s.client_id = c.ident
WHERE NOT EXISTS (
SELECT 1 FROM production_work p WHERE p.ident = o.ident
)
) q ORDER BY due DESC
Here's the query I ended up with:
WITH work_totals AS (
SELECT p.order_id, SUM(p.ud + p.dp + p.swrv + p.sh + p.jmsw + p.sw + p.prrv + p.mhsw + p.bmsw + p.mp + p.pr + p.st) AS total
FROM production_work p
GROUP BY p.order_id
), order_totals AS (
SELECT ident, SUM(ud + dp + swrv + sh + jmsw + sw + prrv + mhsw + bmsw + mp + pr + st) AS total
FROM orders
GROUP BY ident
)
SELECT o.ident, c."name" AS cname, s."name" as sname, o.number, o.created, o.due, o.name, o.ud, o.dp, o.swrv, o.sh, o.jmsw, o.sw, o.prrv, o.mhsw, o.bmsw, o.mp, o.pr, o.st
FROM orders o
INNER JOIN stations s on s.ident = o.station_id
INNER JOIN clients c ON s.client_id = c.ident
INNER JOIN order_totals ot ON o.ident = ot.ident
LEFT OUTER JOIN work_totals w ON o.ident = w.order_id
WHERE w.order_id IS NULL OR ot.total <> w.total
The two queries in your UNION are almost identical so you can merge them into a single query as follows. I just changed the JOIN to the pw subquery to be a OUTER LEFT JOIN - which has the same reslut as your union because I incldued an additional OR clause in the WHERE statement to return these orders that dont have a record in the pw sub-query.
SELECT o.ident, c."name" AS cname, s."name" as sname, o.number, o.created, o.due, o.name, o.ud, o.dp, o.swrv, o.sh, o.jmsw, o.sw, o.prrv, o.mhsw, o.bmsw, o.mp, o.pr, o.st
FROM orders o
INNER JOIN stations s on s.ident = o.station_id
INNER JOIN clients c ON s.client_id = c.ident
LEFT OUTER JOIN (
SELECT p.order_id, SUM(p.ud) AS ud, SUM(p.dp) AS dp, SUM(p.swrv) AS swrv, SUM(p.sh) AS sh, SUM(p.jmsw) AS jmsw, SUM(p.sw) AS sw, SUM(p.prrv) AS prrv,
SUM(p.mhsw) AS mhsw, SUM(p.bmsw) AS bmsw, SUM(p.mp) AS mp, SUM(p.pr) AS pr, SUM(p.st) AS st
FROM production_work p
GROUP BY p.order_id
) pw ON o.ident = pw.order_id
WHERE (o.ud <> pw.ud OR o.dp <> pw.dp OR o.swrv <> pw.swrv OR o.sh <> pw.sh OR o.jmsw <> pw.jmsw OR o.sw <> pw.sw OR o.prrv <> pw.prrv OR
o.mhsw <> pw.mhsw OR o.bmsw <> pw.bmsw OR o.mp <> pw.mp OR o.pr <> pw.pr OR o.st <> pw.st
)
OR pw.order_id IS NULL
ORDER BY due DESC
Queries of this form: Show rows which do not have a match in the other table.
Can be done like this:
select <columns>
from <table1>
left outer join <table2> on <join_condition>
where table2.column IS NULL
This will find rows from table1 which do not have anything in table2 matching the join condition.
For your summing query, I would do something like this...
select table1.order_number, total = sum(table2.order_amount)
from table1
left outer join table2 on table1.order_number = table2.order_number
group by order_number
having total < (some_number) OR total is null
That combines getting orders which have no matches, and getting orders with less than some total order_amount.