My join query is here i want how much % between Sale Price Original Price in MySql query?
SELECT DISTINCT (CASE
WHEN b.method = 'checkmo' THEN 'Check / Money order'
ELSE 'Credit Card (saved)'
END) AS 'Payment Method',a.increment_id as 'Ref-Order Number',a.store_name as 'purchased From (Store)', a.created_at as 'Purchased On',CONCAT (customer_firstname,' ',customer_lastname) as 'Sender-Store Name',CONCAT (customer_firstname,' ',customer_lastname) as 'Attention',c.telephone as 'Phone',c.street as 'Shipping Street',c.city as 'Shipping City',c.region as 'Shipping State',c.postcode as 'Shipping Zip',d.Sku as 'SKU',name as 'Name', round(d.base_price,2) as 'Sale Price', round(e.price,2) as 'Original Price', round(base_grand_total,2) as 'G.T.(Base)',round(grand_total,2) as 'G.T.(Purchased)',round(d.qty_ordered) as 'Product Qty Ordered',status as 'Status',a.coupon_code as 'Coupon Code',a.customer_email as 'Email'
FROM sales_flat_order_item d left outer join sales_flat_order a on d.order_id = a.entity_id left outer join sales_flat_order_payment b on d.order_id = b.entity_id left outer join sales_flat_order_address c on a.customer_id = c.entity_id left outer join catalog_product_index_price
e on d.product_id = e.entity_id where status != 'canceled' and d.base_price > 0 and e.customer_group_id = 0
I solved it by adding round((e.price/d.base_price)*100) as 'Percentage' to the SELECT statement:
SELECT DISTINCT (CASE
WHEN b.method = 'checkmo' THEN 'Check / Money order'
ELSE 'Credit Card (saved)'
END) AS 'Payment Method',a.increment_id as 'Ref-Order Number',a.store_name as 'purchased From (Store)', a.created_at as 'Purchased On',CONCAT (customer_firstname,' ',customer_lastname) as 'Sender-Store Name',CONCAT (customer_firstname,' ',customer_lastname) as 'Attention',c.telephone as 'Phone',c.street as 'Shipping Street',c.city as 'Shipping City',c.region as 'Shipping State',c.postcode as 'Shipping Zip',d.Sku as 'SKU',name as 'Name', round(e.price,2) as 'Original Price', round(d.base_price,2) as 'Sale Price', round((d.base_price/e.price)*100) as 'Percentage', round(base_grand_total,2) as 'G.T.(Base)',round(grand_total,2) as 'G.T.(Purchased)',round(d.qty_ordered) as 'Product Qty Ordered',status as 'Status',a.coupon_code as 'Coupon Code',a.customer_email as 'Email'
FROM sales_flat_order_item d left outer join sales_flat_order a on d.order_id = a.entity_id left outer join sales_flat_order_payment b on d.order_id = b.entity_id left outer join sales_flat_order_address c on a.customer_id = c.entity_id left outer join catalog_product_index_price
e on d.product_id = e.entity_id where status != 'canceled' and d.base_price > 0 and e.customer_group_id = 0
Related
I'm looking for a more efficient way to write this query which displays meta values for an order in a single row. I can't think of a solution myself but before I redesign the database I wanted to see if anyone has any ideas to avoid 11 INNER JOINs. Here is my query which currently takes 20 seconds to load a single result (which is obviously not practical):
SELECT
o1.order_id,
o1.order_status AS 'Order Status',
m3.meta_value AS 'UOP Order Status',
m4.meta_value AS 'UOP Registration Date',
m5.meta_value AS 'UOP Banner Registration',
m6.meta_value AS 'UOP Banner Date',
m7.meta_value AS 'Course Completion Date',
m8.meta_value AS 'Course Grade',
m9.meta_value AS 'Grade Submission Date',
m1.meta_value AS 'First Name',
m2.meta_value AS 'Last Name',
o1.order_date AS 'Order Date',
m10.meta_value,
m11.meta_value,
o1.partner_id AS 'Source'
FROM partner_orders o1
INNER JOIN partner_order_meta m1
ON (o1.order_id = m1.order_id)
INNER JOIN partner_order_meta m2
ON (o1.order_id = m2.order_id)
INNER JOIN partner_order_meta m3
ON (o1.order_id = m3.order_id)
INNER JOIN partner_order_meta m4
ON (o1.order_id = m4.order_id)
INNER JOIN partner_order_meta m5
ON (o1.order_id = m5.order_id)
INNER JOIN partner_order_meta m6
ON (o1.order_id = m6.order_id)
INNER JOIN partner_order_meta m7
ON (o1.order_id = m7.order_id)
INNER JOIN partner_order_meta m8
ON (o1.order_id = m8.order_id)
INNER JOIN partner_order_meta m9
ON (o1.order_id = m9.order_id)
INNER JOIN partner_order_meta m10
ON (o1.order_id = m10.order_id)
INNER JOIN partner_order_meta m11
ON (o1.order_id = m11.order_id)
WHERE m1.meta_key = 'First Name' AND m2.meta_key = 'Last Name' AND m3.meta_key = 'uop_order_status' AND m4.meta_key = 'uop_registration_date' AND m5.meta_key = 'uop_banner_registration' AND m6.meta_key = 'uop_banner_registration_date' AND m7.meta_key = 'course_completion_date' AND m8.meta_key = 'course_grade' AND m9.meta_key = 'grade_submission_date' AND m10.meta_key = 'Course Number' AND m11.meta_key = 'Course Title';
Use grouping:
SELECT
o1.order_id,
o1.order_status AS `Order Status`,
MAX(IF(m.meta_key = 'First Name', m.meta_value, NULL)) AS `First Name`,
MAX(IF(m.meta_key = 'Last Name', m.meta_value, NULL)) AS `Last Name`,
...
FROM partner_orders AS o1
JOIN partner_order_meta AS m ON o1.order_id = m.order_id
GROUP BY o1.order_id
I have this query in MySQL that lists all Moodle courses that have been accessed in the last 2 years and the user (+ their Moodle role) that last accessed it. I'm trying to convert it to PostgreSQL 9.3.22 so it can run on another Moodle LMS I administrate. However, the query fails with the error ERROR: schema "cat" does not exist.
MySQL query:
select cat.id 'category id',
cat.name 'category',
lsl.courseid,
c.fullname 'course fullname',
case when c.visible = '1'
then 'yes'
else 'no'
end as "course visibility",
from_unixtime(max(lsl.timecreated), '%H:%i %D %M %Y') 'lastaccessed',
lsl.userid 'lastaccesseduserid',
u.username 'last accessed by',
case when r.shortname is null
then 'user is not enrolled in this course'
else r.shortname
end 'role'
from prefix_logstore_standard_log lsl
join prefix_course c on c.id = lsl.courseid
join prefix_course_categories cat on cat.id = c.category
join prefix_user u on u.id = lsl.userid
left join prefix_role_assignments ra on ra.contextid = lsl.contextid -- left join in case the last accessed user wasn't enrolled in the course (i.e. admin staff).
left join prefix_role r on r.id = ra.roleid
group by lsl.courseid
having max(lsl.timecreated) > unix_timestamp(date_sub(now(), interval 24 month))
order by lsl.courseid asc
My PostgreSQL conversion attempt:
select cat.id 'category id',
cat.name 'category',
lsl.courseid,
c.fullname 'course fullname',
case when c.visible = '1'
then 'yes'
else 'no'
end as "course visibility",
to_char(to_timestamp(max(lsl.timecreated)), 'HH24:MI DD/MM/YYYY') "last accessed date",
lsl.userid 'lastaccesseduserid',
u.username 'last accessed by',
case when r.shortname is null
then 'user is not enrolled in this course'
else r.shortname
end "role"
from prefix_logstore_standard_log lsl
join prefix_course c on c.id = lsl.courseid
join prefix_course_categories cat on cat.id = c.category
join prefix_user u on u.id = lsl.userid
left join prefix_role_assignments ra on ra.contextid = lsl.contextid -- left join in case the last accessed user wasn't enrolled in the course (i.e. admin staff).
left join prefix_role r on r.id = ra.roleid
group by lsl.courseid
having max(lsl.timecreated) > extract(epoch from now()- interval '2 year')
order by lsl.courseid asc
I checked the database's schema, and the table exists, but I don't understand why this error occurs on the prefix_course_categories table only. I don't know PostgreSQL very well, so your assistance is greatly appreciated!
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)
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
SELECT p.value AS __color__,
milestone AS __group__,
milestone,
priority,
time AS created,
COUNT(t.id) as 'total open tickets',
SUM(c.value) as 'Total Dev LOE',
SUM(d.value) as 'Total QALOE'
FROM ticket t
LEFT JOIN ticket_custom c ON (t.id = c.ticket AND c.name = 'devloe')
LEFT JOIN ticket_custom d ON (t.id = d.ticket AND d.name = 'qaloe')
LEFT JOIN enum p ON p.name = t.priority AND p.type = 'priority'
WHERE t.milestone = '$MILESTONE'
AND status <> 'closed'
GROUP BY milestone, priority, DATE(FROM_UNIXTIME(time/1000000)) DESC
Then add subquery to return the sum total devloe and qaloe for each priority.
Select p.value AS __color__
, milestone AS __group__
, milestone
, priority
, time AS created
, Count(t.id) as 'total open tickets'
, Sum( Case When c.name = 'devloe' Then c.value End ) As 'Total Dev LOE'
, Sum( Case When c.name = 'qaloe' Then c.value End ) As 'Total QALOE'
, PriorityCounts.Total_Dev_LOE As Priority_Total_QALOE
, PriorityCounts.Total_QALOE As Priority_Total_QALOE
From ticket As t
Left Join ticket_custom As c
On t.id = c.ticket
And c.name In('devloe', 'qaloe')
Left Join enum p
On p.name = t.priority
AND p.type = 'priority'
Join (
Select t1.priority,
, Sum( Case When c1.name = 'devloe' Then c1.value End ) As Total_Dev_LOE
, Sum( Case When c1.name = 'qaloe' Then c1.value End ) As Total_QALOE
From ticket As t1
Left Join ticket_custom As c1
On t1.id = c1.ticket
And c1.name In('devloe', 'qaloe')
Group By t1.priority
) As PriorityCounts
On PriorityCounts.priority = t.priority
Where t.milestone = '$MILESTONE'
And status <> 'closed'
Group By milestone, priority, DATE(FROM_UNIXTIME(time/1000000)) DESC
Doesn't answer your question, but you could simplify the query:
SELECT p.value AS __color__,
milestone AS __group__,
milestone,
priority,
time AS created,
COUNT(t.id) as 'total open tickets',
SUM(CASE WHEN c.name = 'devloe' THEN c.value ELSE 0 END) as 'Total Dev LOE',
SUM(CASE WHEN c.name = 'qaloe' THEN c.value ELSE 0 END) as 'Total QALOE'
FROM TICKET t
LEFT JOIN TICKET_CUSTOM c ON c.ticket = t.id
AND c.name IN ('devloe', 'qaloe')
LEFT JOIN ENUM p ON p.name = t.priority
AND p.type = 'priority'
WHERE t.milestone = '$MILESTONE'
AND status <> 'closed'
GROUP BY milestone, priority, DATE(FROM_UNIXTIME(time/1000000)) DESC