ER diagram
ER diagram is attached
I need to get sales invoice invoices.type = 'sales' and invoices.type = 'purchase'
with company name as you can see in select statement
also sales and purchase columns
My query
SELECT jobs.id as jobID,
-- c.name AS Customer,jobs.job_no,
invoices.invoice_due_date,
jobs.id,
( (invoice_items.amount * invoice_items.quantity * invoice_items.exchange_rate )) as Ammount
FROM invoices
INNER JOIN `invoice_items` ON invoices.id = invoice_items.invoice_id
INNER JOIN `jobs` ON jobs.id = invoices.job_id
-- INNER JOIN `company` as c ON c.company_id = jobs.company_id -- jobs and company.
WHERE invoices.type = 'sales'
-- new conditions
AND MONTH(jobs.created_at) = '3'
AND YEAR(jobs.created_at) = '2017'
AND jobs.status > 0
AND jobs.complete_job > 0
AND jobs.completed_at IS NOT NULL
AND invoice_items.deleted_at IS NULL
GROUP BY jobs.job_no
ORDER BY invoices.invoice_due_date DESC
Try this updated...
SELECT jobs.id as jobID,
C.name AS Customer,jobs.job_no,
invoices.invoice_due_date,
jobs.id,
( (invoice_items.amount * invoice_items.quantity *invoice_items.exchange_rate )) as Ammount,
CASE invoices.type
WHEN 'sales' THEN 'S'
ELSE 'P'
END as trans_type
FROM invoices
INNER JOIN `invoice_items` ON invoices.id = invoice_items.invoice_id
INNER JOIN `jobs` ON jobs.id = invoices.job_id
LEFT OUTER JOIN `company` as C ON C.company_id = jobs.company_id
WHERE (invoices.type = 'sales' OR invoices.type = 'purchase') AND (MONTH(jobs.created_at) = '3') AND (YEAR(jobs.created_at) = '2017') AND (jobs.status > 0) AND (jobs.complete_job > 0) AND (jobs.completed_at IS NOT NULL)
Related
Usually when joining between two tables where there is a one-to-many relationship there will be duplicates created
Which i am joining with order-activities table
query = f"""
SELECT {time_period_column_name},
store_id,
st.name as store_name,
shopper_id,
first_names,
last_name,
total_orders,
total_items_picked,
shopper_request_time,
shopper_accepted_time,
shopping_completed_time,
ROUND(total_shopping_minutes, 2) as total_shopping_minutes,
ROUND(min_shopping_minutes, 2) AS min_shopping_minutes,
ROUND(max_shopping_minutes, 2) AS max_shopping_minutes,
ROUND(average_shopping_minutes, 2) as average_shopping_minutes,
ROUND(total_shopping_minutes / total_orders, 2) as minutes_per_order,
ROUND(total_items_picked / total_shopping_minutes, 2) as shopping_efficiency,
ROUND(average_order_zar, 2) as average_order_zar
FROM (
SELECT o.shopper_id,
o.store_id,
{time_period_column_name},
Count(1) AS total_orders,
TIMEDIFF(Max(o.shopper_request_stop), Max(o.shopper_request_start)) AS shopper_request_time,
TIMEDIFF(Max(o.shopper_accepted_stop), Max(o.shopper_accepted_start)) AS shopper_accepted_time,
TIMEDIFF(Max(o.shopping_completed_stop), Max(o.shopping_completed_start)) AS shopping_completed_time,
Sum(order_items_picked) AS total_items_picked,
AVG(o.total) / 100.0 AS average_order_zar,
Min(shopping_minutes) AS min_shopping_minutes,
Max(shopping_minutes) AS max_shopping_minutes,
Avg(shopping_minutes) AS average_shopping_minutes,
Sum(shopping_minutes) AS total_shopping_minutes
FROM (
SELECT oo.shopper_id,
oo.store_id,
oo.total,
order_item_counts.order_items_picked,
date_format(oo.created_at, '{time_period_format_str}') AS {time_period_column_name},
IF(oa.status_code = 'shopper-request', oa.created_at, NULL) AS shopper_request_start,
IF(oa.prev_status_code = 'shopper-request', oa.created_at, NULL) AS shopper_request_stop,
IF(oa.status_code = 'shopper-accepted', oa.created_at, NULL) AS shopper_accepted_start,
IF(oa.prev_status_code = 'shopper-accepted', oa.created_at, NULL) AS shopper_accepted_stop,
IF(oa.status_code = 'shopping-completed', oa.created_at, NULL) AS shopping_completed_start,
IF(oa.prev_status_code = 'shopping-completed', oa.created_at, NULL) AS shopping_completed_stop,
(TIMESTAMPDIFF(MICROSECOND, oo.started_shopping_at,
oo.finished_shopping_at) / 6E7) AS shopping_minutes
FROM {self.market_db}.orders as oo
LEFT JOIN (
SELECT order_id, Sum(picked) as order_items_picked FROM {self.market_db}.order_items oi
WHERE oi.store_id IN ({store_ids_str})
GROUP BY oi.order_id
) order_item_counts ON oo.id = order_item_counts.order_id
LEFT JOIN {self.market_db}.order_activities as oa ON oo.id = oa.order_id
WHERE (oa.prev_status_code IN ('shopper-request',
'shopper-accepted',
'shopping',
'shopping-completed',
'collected',
'delivery')
OR oa.status_code IN ('shopper-request',
'shopper-accepted',
'shopping',
'shopping-completed',
'collected',
'delivery'))
AND oa.created_at >= '{start_date}'
AND oa.created_at < '{end_date}'
AND oo.started_shopping_at IS NOT NULL
AND oo.finished_shopping_at IS NOT NULL
AND oa.status_code <> oa.prev_status_code
AND oo.store_id IN ({store_ids_str})
) AS o
GROUP BY shopper_id, {time_period_column_name}, store_id
HAVING total_orders >= 1
) AS oc
INNER JOIN {self.users_db}.users us
ON us.id = oc.shopper_id
INNER JOIN {self.market_db}.stores st
ON st.id = oc.store_id
ORDER BY store_id DESC, {time_period_column_name} DESC, total_orders DESC;
"""
rows = self.run_market_query(query=query)
return rows
i have SQL query. I would like to orderby this by parent category. But i return only default category. I would like to know if i can
ORDER BY SELECT id_parent FROM cats WHERE id_category = id_default_category
Here is my query :
SELECT cp.`id_product_attribute`,
cp.`id_product`, cp.`quantity` AS cart_quantity,
cp.id_shop, pl.`name`,
p.`is_virtual`,
pl.`description_short`,
pl.`available_now`,
pl.`available_later`,
product_shop.`id_category_default`,
p.`id_supplier`,
p.`id_manufacturer`,
product_shop.`on_sale`,
product_shop.`ecotax`,
product_shop.`additional_shipping_cost`,
product_shop.`available_for_order`,
product_shop.`price`,
product_shop.`active`,
product_shop.`unity`,
product_shop.`unit_price_ratio`,
stock.`quantity` AS quantity_available,
p.`width`,
p.`height`,
p.`depth`,
stock.`out_of_stock`,
p.`weight`,
p.`date_add`,
p.`date_upd`,
IFNULL(stock.quantity, 0) as quantity,
pl.`link_rewrite`,
cl.`link_rewrite` AS category,
CONCAT(LPAD(cp.`id_product`, 10, 0),
LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0),
IFNULL(cp.`id_address_delivery`, 0)) AS unique_id,
cp.id_address_delivery,
product_shop.advanced_stock_management,
ps.product_supplier_reference supplier_reference
FROM `ps_cart_product` cp
LEFT JOIN `ps_product` `p` ON p.`id_product` = cp.`id_product`
INNER JOIN `ps_product_shop` product_shop ON (product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)
LEFT JOIN `ps_product_lang` `pl` ON p.`id_product` = pl.`id_product`
AND pl.`id_lang` = 1 AND pl.id_shop = cp.id_shop
LEFT JOIN `ps_category_lang` `cl` ON product_shop.`id_category_default` = cl.`id_category`
AND cl.`id_lang` = 1 AND cl.id_shop = cp.id_shop
LEFT JOIN `ps_product_supplier` `ps` ON ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`
LEFT JOIN ps_sanishopstock_available stock
ON (stock.id_product = cp.id_product AND stock.id_product_attribute = IFNULL(`cp`.id_product_attribute, 0) AND stock.id_shop = 1 AND stock.id_shop_group = 0 )
WHERE cp.`id_cart` = 757
ORDER BY product_shop.id_category_default ASC, cp.id_product, cp.date_add ASC;
There is a lot of different table, i'm lost !
If someone have any idea.
Thanks a lot !
Yes. But like any subquery, you need parentheses:
ORDER BY (SELECT c.id_parent FROM cats c WHERE id_category = id_default_category)
I would also qualify the column names in the WHERE, but I don't know where they come from.
i am developing a LMS system for an institute
and i am trying to develop a recovery report on the end of month
the report contains student name total fee package, total received, total receiveable, current month pending installment
here is the installment data of a student with his admission id
and this is the ledger data from where ican pick the fee package and total receiveable fees
and i am using this query for recovery report
SELECT
SUM(l.dr)-SUM(l.cr) as sum_remaining,
f.dr as fee_package,
SUM(i.payment) as this_month_install,
a.reg_id, s.fname
FROM
ledger l, ledger f, student_data s,
admissions a LEFT OUTER JOIN installments i ON a.admissionid = i.admissionid
WHERE
a.admissionid = '58ac4b5421488' AND
a.reg_id = s.reg_id AND
l.reference = '58ac4b5421488' AND
l.details <> 'registration fee' AND
f.reference = '58ac4b5421488' AND
f.details = 'Fee Package' AND
i.install_no <> '1' AND
MONTH(i.pay_date) = '04' AND
YEAR(i.pay_date) = '2017'
GROUP BY a.admissionid
and its giving the result like this
but the result should be like
sum_remaining = 10000
and this_month_install = 10000
please help me to sort out this problem
Thanks in advance
you should start from admission and use inner join for the others table (left join for installments)
SELECT
SUM(l.dr)-SUM(l.cr) as sum_remaining,
f.dr as fee_package,
SUM(i.payment) as this_month_install,
a.reg_id,
s.fname
FROM admissions a
Inner JOIN ledger f ON f.reference = a.admissionid AND f.details = 'Fee Package'
INNER JOIN ledger l ON l.reference = a.admissionid AND l.details <> 'registration fee'
INNER JOIN student_data s ON a.reg_id = s.reg_id
LEFT JOIN installments i ON a.admissionid = i.admissionid AND i.install_no <> '1'
WHERE a.admissionid = '58ac4b5421488'
AND MONTH(i.pay_date) = '04'
AND YEAR(i.pay_date) = '2017'
GROUP BY a.admissionid
you have two row in installments table that match .. try filter just one
SELECT
SUM(l.dr)-SUM(l.cr) as sum_remaining,
f.dr as fee_package,
SUM(i.payment) as this_month_install,
a.reg_id,
s.fname
FROM admissions a
Inner JOIN ledger f ON f.reference = a.admissionid AND f.details = 'Fee Package'
INNER JOIN ledger l ON l.reference = a.admissionid AND l.details <> 'registration fee'
INNER JOIN student_data s ON a.reg_id = s.reg_id
LEFT JOIN installments i ON a.admissionid = i.admissionid
AND i.install_no not in ( '1', '2')
WHERE a.admissionid = '58ac4b5421488'
AND MONTH(i.pay_date) = '04'
AND YEAR(i.pay_date) = '2017'
GROUP BY a.admissionid
i have done this with a sub query
thanks all
select a.admissionid, s.fname,
sum(l.dr)-SUM(l.cr) as sum_remaining, i.*,
f.dr as fee_package from student_data s,
ledger l, ledger f, admissions a
RIGHT outer join (select admissionid,
sum(payment) as this_month_install
from
installments g where g.install_no <> '1' and MONTH(g.pay_date) = '04' and YEAR(g.pay_date) = '2017' group by g.admissionid) i
ON
i.admissionid = a.admissionid where a.reg_id = s.reg_id and
a.status = 'studying' and a.course = 'PH' and
a.campus = 'CIFSD01' and l.reference = a.admissionid and
l.details <> 'registration fee' and f.reference = a.admissionid
and f.details = 'Fee Package' GROUP BY a.std_id
in the below code there are multiple entries in 'leads' table with the same 'account_id'. I want it to return a single row - the one with the minimal value of another field 'date_entered'. I cannot use 'group by' on account_id as I intend to use 'group by' on BU and get summation accordingly. Please help.
select uc.business_unit_dp_c,
FORMAT(SUM(CASE
WHEN lc.source_leads_c not in ('Discovery','Discovery SuperEmail','Self Generated','Partner','Channel_Partner') and k.id<>'' THEN k.order_value
WHEN lc.source_leads_c not in ('Discovery','Discovery SuperEmail','Self Generated','Partner','Channel_Partner') and s.id<>'' THEN s.sivr_aiv_inr
ELSE 0
END),0)
as Online,
FORMAT(SUM(CASE
WHEN lc.source_leads_c in ('Discovery', 'Discovery SuperEmail') and k.id<>'' THEN k.order_value
WHEN lc.source_leads_c in ('Discovery', 'Discovery SuperEmail') and s.id<>'' THEN s.sivr_aiv_inr
ELSE 0
END),0)
as Discovery,
FORMAT(SUM(CASE
WHEN lc.source_leads_c in ('Partner','Channel_Partner') and k.id<>'' THEN k.order_value
WHEN lc.source_leads_c in ('Partner','Channel_Partner') and s.id<>'' THEN s.sivr_aiv_inr
ELSE 0
END),0)
as Self_Generated_CP
from opportunities as o
left join opportunities_cstm as oc on o.id=oc.id_c
left join opportunities_knw_caf_1_c as ok on o.id=ok.opportunities_knw_caf_1opportunities_ida
left join knw_caf as k on ok.opportunities_knw_caf_1knw_caf_idb=k.id
left join opportunities_knw_sivr_caf_1_c as os on os.opportunities_knw_sivr_caf_1opportunities_ida=o.id
left join knw_sivr_caf as s on s.id=os.opportunities_knw_sivr_caf_1knw_sivr_caf_idb
left join accounts_opportunities as ao on ao.opportunity_id=o.id
left join leads as l on l.account_id=ao.account_id and l.account_id <> ''
left join leads_cstm as lc on lc.id_c=l.id
left join users_cstm as uc on uc.id_c=o.assigned_user_id
where o.sales_stage='clw' and
(k.id<>'' or s.id<>'') and o.jira_raise_date <> '' and
(o.tranjection_type in ('Fresh Plan / New Customer','Number Activation','Revival','Balance Amount') or o.transaction_sivr in ('Paid Project','Number Allocation','New Feature')) and
o.jira_raise_date between '2016-06-01' and curdate()
group by uc.business_unit_dp_c
Write SQL just as you described
Select *
from from opportunities o
left join opportunities_cstm oc
on o.id = oc.id_c
left join opportunities_knw_caf_1_c ok
on o.id = ok.opportunities_knw_caf_1opportunities_ida
left join knw_caf k
on ok.opportunities_knw_caf_1knw_caf_idb = k.id
left join opportunities_knw_sivr_caf_1_c os
on os.opportunities_knw_sivr_caf_1opportunities_ida=o.id
left join knw_sivr_caf s
on s.id = os.opportunities_knw_sivr_caf_1knw_sivr_caf_idb
left join accounts_opportunities ao
on ao.opportunity_id=o.id
left join leads l
on l.account_id=ao.account_id
and l.account_id <> ''
left join leads_cstm lc
on lc.id_c = l.id
left join users_cstm uc
on uc.id_c = o.assigned_user_id
where o.sales_stage = 'clw' and
and (k.id <> '' or s.id <> '')
and o.jira_raise_date <> ''
and (o.tranjection_type in
('Fresh Plan / New Customer',
'Number Activation','Revival','Balance Amount') or
o.transaction_sivr in
('Paid Project','Number Allocation','New Feature'))
and o.jira_raise_date between '2016-06-01' and curdate()
-- next, add this additional predicate to Where clause...
use table w/DateEntered column
and date_entered =
(Select Min(date_entered)
From accounts_opportunities os
join tableWithDateEntered dr -- Table w/DateEntered
on ????? -- proper join criteria here
Where os.account_id = l.account_id)
--- or as constructed by op ( and simplified by me, since both account_id and date_entered are in table leads, that's the only table that needs to be referenced in the subquery).....
and l.date_entered =
(select min(date_entered)
from leads
where account_id = l.account_id)
select min(C.date),C.Customer_Code from (
select InvoiceNo,month(InvoiceDate) as date,Customer_Code,Createddate from tbl_Invoices A Inner Join tbl_customer B on A.customer_Code=B.CustomerCode
where YEAR(InvoiceDate)='2017'
and CustomerCode not in (select CustomerCode from tbl_customer where year(createddate) in (year(getdate())))
and CustomerCode not in (select customer_Code from tbl_Invoices where year(InvoiceDate) in (year(getdate())-1))
and CustomerCode in (select customer_Code from tbl_Invoices where year(InvoiceDate) not in (year(getdate())))
--group by Customer_Code,Createddate,InvoiceNo
)C group by C.Customer_Code
Hi I have run into a dilemma, I am doing this query:
SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories, pr.promo_name, pr.add_value_text, c.contract_id, c.cmeal_plan, c.cmin_markup, c.civa, c.tax_include, c.hotel_id, hi.hname, hi.hstars, im.image_file, pl.plan_name, ra.price
FROM contracts AS c
INNER JOIN hotel_info AS hi ON hi.hotel_id = c.hotel_id AND hi.destination_id = '6460'
INNER JOIN images AS im ON im.foreign_id = hi.hotel_id
INNER JOIN meal_plan AS pl ON pl.plan_code = c.cmeal_plan AND pl.lang = '1'
INNER JOIN hotel_categories AS hc ON hc.hotel_id = hi.hotel_id
INNER JOIN categories AS ca ON ca.category_code = hc.category_code AND ca.lang = '1'
LEFT JOIN
(SELECT
r.hotel_id, AVG(r.double) AS price
FROM
rates AS r ) AS ra
ON ra.hotel_id = hi.hotel_id
LEFT JOIN promotions AS pr ON pr.hotel_id = hi.hotel_id AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0 AND pr.book_start <= '2012-11-01' AND pr.book_end >= '2012-11-02' AND travel_start <= '2012-11-23' AND travel_end >= '2012-11-30' AND pr.lang = '1'
WHERE c.cstart <= '2012-11-01' AND c.cend >= '2012-11-01'
AND hi.status = '1'
AND im.type ='1'
GROUP BY hi.hotel_id
I am getting all the desired results except for the sub select query.. each hotel has a price but it is only giving me back one result and the rest are all null. Is there an error in my query? If any additional information is needed please let me know and thank you in advance for any help!
You are missing the GROUP BY in your subquery, so MySQL will only return one-value. If you want all hotel_id's then you need to GROUP BY that field:
SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories,
pr.promo_name,
pr.add_value_text,
c.contract_id,
c.cmeal_plan,
c.cmin_markup,
c.civa,
c.tax_include,
c.hotel_id,
hi.hname,
hi.hstars,
im.image_file,
pl.plan_name,
ra.price
FROM contracts AS c
INNER JOIN hotel_info AS hi
ON hi.hotel_id = c.hotel_id
AND hi.destination_id = '6460'
INNER JOIN images AS im
ON im.foreign_id = hi.hotel_id
INNER JOIN meal_plan AS pl
ON pl.plan_code = c.cmeal_plan
AND pl.lang = '1'
INNER JOIN hotel_categories AS hc
ON hc.hotel_id = hi.hotel_id
INNER JOIN categories AS ca
ON ca.category_code = hc.category_code
AND ca.lang = '1'
LEFT JOIN
(
SELECT r.hotel_id, AVG(r.double) AS price
FROM rates AS r
GROUP BY r.hotel_id <-- add a GROUP BY hotel_id then you will get avg() for each hotel
) AS ra
ON ra.hotel_id = hi.hotel_id
LEFT JOIN promotions AS pr
ON pr.hotel_id = hi.hotel_id
AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0
AND pr.book_start <= '2012-11-01'
AND pr.book_end >= '2012-11-02'
AND travel_start <= '2012-11-23'
AND travel_end >= '2012-11-30'
AND pr.lang = '1'
WHERE c.cstart <= '2012-11-01'
AND c.cend >= '2012-11-01'
AND hi.status = '1'
AND im.type ='1'
GROUP BY hi.hotel_id