How to run two where clauses inside a Join? - mysql

Please check the below code.
SELECT
`order`.idorder
, order_status_code.idorder_status_code
, order_status_code.order_status_code
, user.iduser
, `order`.required_delivery_date
, `order`.cancel
, `order`.date_created
, `order`.last_updated
, COUNT(order_item.idorder_item)
from
`order`
INNER JOIN order_status_code
ON `order`.idorder_status_code = order_status_code.idorder_status_code
INNER JOIN user
ON `order`.iduser = user.iduser
INNER JOIN order_item
ON order_item.idorder = `order`.`idorder`
WHERE
`order`.iduser = 1
In here, I want the COUNT(order_item.idorder_item) to return the number of items under the idorder. In other words, if I run that SQL Part along, that would be like below
SELECT
COUNT(`idorder_item`)
from
order_item
where
idorder = 1
How can I get this done in my main query?

SELECT `order`.idorder,
order_status_code.idorder_status_code,
order_status_code.order_status_code,
user.iduser,
`order`.required_delivery_date,
`order`.cancel,
`order`.date_created,
`order`.last_updated,
COUNT(order_item.idorder_item),
(SELECT COUNT(`idorder_item`)
from order_item
where idorder=1) as count_idorder_item
from `order`
INNER JOIN order_status_code ON `order`.idorder_status_code = order_status_code.idorder_status_code
INNER JOIN user ON `order`.iduser = user.iduser
INNER JOIN order_item ON order_item.idorder = `order`.`idorder`
WHERE `order`.iduser= 1

Related

SQL UPDATE TABLE from SELECT query from other tables

I have bd hf3 and 5 tables there:
active_preset with columns (id , preset_id)
preset with columns (id , birja_id, trend_id, fractal, interval_up)
birja with columns (id , name)
trend with columns (id , name)
uq_active_preset with columns (id , birja, trend, fractal, interval_up)
In table preset I have a few records. Some of them are in table active_preset by foreign key preset_id. In table active_preset a few records exist once , a few more than once.
I need to update table uq_active_preset with records from table active_preset disregarding repetitions of records if they are present.
I did query from active_preset and it works good:
SELECT
b.name AS birja, p.fractal AS fractal , tre.name AS trend, p.interval_up AS interval_up
FROM hf3.active_preset AS ap
INNER JOIN hf3.preset AS p on p.id = ap.preset_id
INNER JOIN hf3.birja AS b on b.id = p.birja_id
INNER JOIN hf3.trend AS tre on tre.id = p.trend_id
GROUP BY b.name, p.fractal, tre.name, p.interval_up
HAVING COUNT(*) >= 1
But I don't know how to update uq_active_preset
I tried this and it returns syntax error:1064 :
UPDATE hf3.uq_active_preset uap SET
uap.birja = st.birja ,
uap.fractal = st.fractal,
uap.trend = st.trend,
uap.interval_up = st.interval_up,
FROM (SELECT b.name AS birja, p.fractal AS fractal , tre.name AS trend, p.interval_up AS interval_up
from hf3.active_preset AS ap
INNER JOIN hf3.preset AS p on p.id = ap.preset_id
INNER JOIN hf3.birja AS b on b.id = p.birja_id
INNER JOIN hf3.trend AS tre on tre.id = p.trend_id
GROUP BY b.name, p.fractal, tre.name, p.interval_up
HAVING COUNT(*) >= 1
) st
when you make an update using from is like you join the updated table with your query result. So, you need also a where statement in order to tell where those two are connected. Also, don't use alias of your updated table on set statement.
You need something like that:
UPDATE hf3.uq_active_preset uap SET birja=st.birja,fractal=st.fractal,trend=st.trend,interval_up=st.interval_up
FROM (SELECT b.name AS birja, p.fractal AS fractal , tre.name AS trend, p.interval_up AS interval_up
from hf3.active_preset AS ap
INNER JOIN hf3.preset AS p on p.id = ap.preset_id
INNER JOIN hf3.birja AS b on b.id = p.birja_id
INNER JOIN hf3.trend AS tre on tre.id = p.trend_id
GROUP BY b.name, p.fractal, tre.name, p.interval_up
HAVING COUNT(*) >= 1
) st
where uap.fkey=st.fkey

Mysql Select unique record based on multiple columns and display only group and sum amount

Hi I am trying to query a table that conatains multiple duplicates on Code,Amount and Status How will I do this if I only one to get a result group according to the client_group name and get the sum of amount under that group
SELECT `client`.`client_group`
, FORMAT(SUM(`Data_result`.`Data_result_amount` ),2) as sum
FROM
`qwer`.`Data_result`
INNER JOIN `qwer`.`Data`
ON (`Data_result`.`Data_result_lead` = `Data`.`Data_id`)
INNER JOIN `qwer`.`Data_status`
ON (`Data_result`.`Data_result_status_id` = `Data_status`.`Data_status_id`)
INNER JOIN `qwer`.`client`
ON (`Data`.`Data_client_id` = `client`.`client_id`)
WHERE `Data_status`.`Data_status_name` IN ('PAID') AND MONTH(`Data_result`.`result_ts`) = MONTH(CURRENT_DATE())
AND YEAR(`Data_result`.`result_ts`) = YEAR(CURRENT_DATE())
GROUP BY `client`.`client_group`
Result of said query:
Table
Try to distinct before run the 'sum' check whether this solve your problem
SELECT `client_group` , FORMAT(SUM(`Data_result_amount` ),2) as sum from (
SELECT DISTINCT `client`.`client_group` , `Data_result`.`Data_result_amount`
FROM
`qwer`.`Data_result`
INNER JOIN `qwer`.`Data`
ON (`Data_result`.`Data_result_lead` = `Data`.`Data_id`)
INNER JOIN `qwer`.`Data_status`
ON (`Data_result`.`Data_result_status_id` = `Data_status`.`Data_status_id`)
INNER JOIN `qwer`.`client`
ON (`Data`.`Data_client_id` = `client`.`client_id`)
WHERE `Data_status`.`Data_status_name` IN ('PAID') AND MONTH(`Data_result`.`result_ts`) = MONTH(CURRENT_DATE())
AND YEAR(`Data_result`.`result_ts`) = YEAR(CURRENT_DATE())
) T
GROUP BY `client_group`
you can check the query here http://sqlfiddle.com/#!9/36a3f8/6

inner join in Sql Subquery

I am trying to run this query with using subquery but not able to fetch my result .is any one here to help me in geting it correct.
SELECT u.uv_id ID
, d.sd_code Code
, u.uv_name Title
, u.uv_nirf Nirf
, (SELECT sd_code
FROM vm_university_type t
JOIN vm_seo_detail d
ON t.ut_id = d.sd_ty_id
AND d.sd_ty = 'vm_university_type') AS 'University Type'
, a.ab_name 'Approved By'
, u.uv_seats Seats
, g.ug_name 'University Group'
FROM vm_universities u
JOIN vm_seo_detail d
ON u.uv_id = d.sd_ty_id
AND d.sd_ty = 'vm_universities'
JOIN vm_university_type t
ON u.uv_ut_id = t.ut_id
JOIN vm_approved_by a
ON u.uv_ab_id = a.ab_id
JOIN vm_caste c
ON u.uv_c_id = c.caste_id
JOIN vm_university_groups g
ON u.uv_ug_ids = g.ug_id;
i got this error Subquery returns more than 1 row
(SELECT `sd_code` FROM vm_university_type INNER JOIN vm_seo_detail ON (vm_university_type.ut_id = vm_seo_detail.sd_ty_id AND vm_seo_detail.sd_ty = 'vm_university_type') WHERE vm_university_type.ut_id=vm_universities.uv_ut_id ) AS 'University Type' ,
You do not need subquery at all. The column Code in SELECT statement contains University Type
Try below query.
SELECT vm_universities.uv_id AS 'ID' , vm_seo_detail.sd_code AS 'Code',
vm_universities.uv_name AS 'Title' , vm_universities.uv_nirf AS 'Nirf',
vm_approved_by.ab_name AS 'Approved By' , vm_universities.uv_seats as 'Seats',
vm_university_groups.ug_name AS 'University Group'
FROM vm_universities INNER JOIN vm_seo_detail
ON (vm_universities.uv_id = vm_seo_detail.sd_ty_id
AND vm_seo_detail.sd_ty = 'vm_universities')
INNER JOIN vm_university_type
ON (vm_universities.uv_ut_id = vm_university_type.ut_id)
INNER JOIN vm_approved_by
ON (vm_universities.uv_ab_id = vm_approved_by.ab_id)
INNER JOIN vm_caste
ON (vm_universities.uv_c_id = vm_caste.caste_id)
INNER JOIN vm_university_groups
ON (vm_universities.uv_ug_ids = vm_university_groups.ug_id);
SELECT `sd_code` FROM vm_university_type INNER JOIN vm_seo_detail ON (vm_university_type.ut_id = vm_seo_detail.sd_ty_id AND vm_seo_detail.sd_ty = 'vm_university_type')
looks like you forgot WHERE section in subquery, that will bind it to main query. something like
WHERE vm_university_type.ut_id=vm_universities.uv_ut_id
ps. and why you need this subquery at all, if you already join with vm_university_type in main query?

Getting the latest date from a id

I run the above sql statement and i got this.[IMG]http://i1093.photobucket.com/albums/i422/walkgirl_1993/asd-1_zps5506632e.jpg[/IMG] i'm trying display the latest date which you can see the 3 and 4. For caseid 3, it should display the latest row which is the 2012-12-20 16:12:36.000. I tried using group by, order by. Google some website said to use rank but i'm not sure about the rank as i dont really get rank. Some suggestions?
select [Case].CaseID, Agent.AgentName, Assignment.Description, A.AgentName as EditedBy, A.DateEdited from Agent inner join [Case-Agent] on [Case-Agent].AgentID = Agent.AgentID inner join [Assignment] on Assignment.AssignmentID = [Case-Agent].AssignmentID inner join [Case] on [Case].CaseID = [Case-Agent].CaseID inner join (select EditedCase.CaseID, [EditedCase].DateEdited, [Agent].AgentName from EditedCase inner join [Agent] on [Agent].AgentID = [EditedCase].AgentID) A on A.CaseID = [Case].CaseID where [Assignment].AssignmentID = 0
To do it using RANK you just need to add the RANK to the subquery and get to rank the DateEdited for each CaseID and Agent and then in the main query put a WHERE clause to only select rows where the rank is 1. I think I have got the partition clause right - its a bit hard without seeing your data.
Like this:
SELECT
[Case].CaseID
,Agent.AgentName
,Assignment.Description
,A.AgentName AS EditedBy
,A.DateEdited
FROM Agent
INNER JOIN [Case-Agent] ON [Case-Agent].AgentID = Agent.AgentID
INNER JOIN [Assignment] ON Assignment.AssignmentID = [Case-Agent].AssignmentID
INNER JOIN [Case] ON [Case].CaseID = [Case-Agent].CaseID
INNER JOIN (SELECT
EditedCase.CaseID
,[EditedCase].DateEdited
,[Agent].AgentName
,RANK ( ) OVER (PARTITION BY EditedCase.CaseID, [Agent].AgentName
ORDER BY [EditedCase].DateEdited DESC ) AS pos
FROM EditedCase
INNER JOIN [Agent] on [Agent].AgentID = [EditedCase].AgentID) A on A.CaseID = [Case].CaseID
WHERE [Assignment].AssignmentID = 0
AND pos = 1
You could also change the sub query into an aggregate query that brings back the MAX date like this:
SELECT
[Case].CaseID
,Agent.AgentName
,Assignment.Description
,A.AgentName AS EditedBy
,A.DateEdited
FROM Agent
INNER JOIN [Case-Agent] ON [Case-Agent].AgentID = Agent.AgentID
INNER JOIN [Assignment] ON Assignment.AssignmentID = [Case-Agent].AssignmentID
INNER JOIN [Case] ON [Case].CaseID = [Case-Agent].CaseID
INNER JOIN (SELECT
EditedCase.CaseID
,MAX([EditedCase].DateEdited) AS DateEdited
,[Agent].AgentName
FROM EditedCase
INNER JOIN [Agent] on [Agent].AgentID = [EditedCase].AgentID
GROUP BY
EditedCase.CaseID
,[Agent].AgentName) A on A.CaseID = [Case].CaseID
WHERE [Assignment].AssignmentID = 0
AND pos = 1
You were on the right track; you need to use a ranking function here, for example row_number():
with LatestCase as
(
select [Case].CaseID
, Agent.AgentName
, Assignment.Description
, A.AgentName as EditedBy
, A.DateEdited
, caseRank = row_number() over (partition by [Case].CaseID order by A.DateEdited desc)
from Agent
inner join [Case-Agent] on [Case-Agent].AgentID = Agent.AgentID
inner join [Assignment] on Assignment.AssignmentID = [Case-Agent].AssignmentID
inner join [Case] on [Case].CaseID = [Case-Agent].CaseID
inner join
(
select EditedCase.CaseID
, [EditedCase].DateEdited
, [Agent].AgentName
from EditedCase
inner join [Agent] on [Agent].AgentID = [EditedCase].AgentID
) A on A.CaseID = [Case].CaseID where [Assignment].AssignmentID = 0
)
select *
from LatestCase
where caseRank = 1

How to optimize this nested SQL query

Here is the database schema:
[redacted]
I'll describe what I'm doing with the query below:
Innermost query: Select all the saleIds satisfying the WHERE conditions
Middle query: Select all the productIds that were a part of the saleId
Outermost query: SUM the products.cost and select the vendors.name.
And here is the SQL query I came up with:
SELECT vendors.name AS Company
, SUM(products.cost) AS Revenue
FROM
products
INNER JOIN sold_products
ON (products.productId = sold_products.productId)
INNER JOIN vendors
ON (products.vendorId = vendors.vendorId)
WHERE sold_products.productId IN (
SELECT sold_products.productId
FROM
sold_products
WHERE sold_products.saleId IN (
SELECT sales.saleId
FROM
markets
INNER JOIN vendors
ON (markets.vendorId = vendors.vendorId)
INNER JOIN sales_campaign
ON (sales_campaign.marketId = markets.marketId)
INNER JOIN packet_headers
ON (sales_campaign.packetHeaderId = packet_headers.packetHeaderId)
INNER JOIN packet_details
ON (packet_details.packetHeaderId = packet_headers.packetHeaderId)
INNER JOIN sales
ON (sales.packetDetailsId = packet_details.packetDetailsId)
WHERE vendors.customerId=60
)
)
GROUP BY Company
ORDER BY Revenue DESC;
Any help in optimizing this?
Since you are just using inner joins you normally simplify the query to smth like this:
SELECT ve.name AS Company
, SUM(pr.cost) AS Revenue
FROM products pr
, sold_products sp
, vendors ve
, markets ma
, sales_campaign sc
, packet_headers ph
, packet_details pd
, sales sa
Where pr.productId = sp.productId
And pr.vendorId = ve.vendorId
And ve.vendorId = ma.vendorId
And sc.marketId = ma.marketId
And sc.packetHeaderId = ph.packetHeaderId
And pd.packetHeaderId = ph.packetHeaderId)
And sa.packetDetailsId = pd.packetDetailsId
And ve.customerId = 60
GROUP BY ve.Company
ORDER BY pr.Revenue DESC;
Please try if this works and if it is faster and let me know.