I have query that working perfectly.but now there is situation where i have to join 2 query in case statement.but problem is one of the query is in already use.So my question how do i add this two sql in one sql
My original sql is
SELECT
tc.dentist_id,md.vendor_no,pl.pack_trans_id,tc.agent_dentist,md.company_name,md.contact,md.phone_no,sql1.image_path,sql1.metal_id,sql1.expect_more,sql1.how_long_acquire,tc.check_amt,tc.check_date_sent,tc.check_no
FROM tbl_check tc
LEFT JOIN tbl_mst_dentist md ON tc.dentist_id=md.dentist_id
LEFT JOIN tbl_pack_list pl ON tc.pack_id=pl.pack_id
LEFT JOIN (SELECT image_path,pack_id,metal_id,expect_more,how_long_acquire FROM
tbl_metals_list GROUP BY pack_id
)sql1 ON tc.pack_id=sql1.pack_id
WHERE tc.sale_agent_id = '3' AND tc.paying_percent !=0
Now i have to add 2 sql statement in the above statement
if(tc.agent_dentist=a) select sa.* ,sm.state_code from tbl_sales_agent
as sa,tbl_mst_state as sm where sa.sales_agent_id = '3' AND
sa.state=sm.state_name else select * from tbl_mst_dentist where
dentist_id =tc.dentist_id
second table already is in use.Is it possible? Thanks in advance
yes, you can use an ALIAS with a different name. E.g. TABLE AS ANY_ALIAS.
SELECT *
FROM t1
JOIN t2 AS alias_a ON (alias_a.t1_id = t1.id)
JOIN t2 AS alias_b ON (alias_b.t1_id = t1.id)
Note that in the absence of any aggregating functions, the use of GROUP BY in this query...
SELECT image_path
, pack_id
, metal_id
, expect_more
, how_long_acquire
FROM tbl_metals_list
GROUP
BY pack_id
...makes little sense. Perhaps you meant SELECT DISTINCT...?
Related
How to implement WHERE conditions in LEFT_JOIN. My query is:
SELECT t1.company_short_name, COUNT(t2.user_ip_address) as chart_accessed
FROM tblcompanymaster t1
LEFT JOIN tblhistorymaster t2 ON t1.row_id = t2.company_id
WHERE t2.user_last_request_time BETWEEN 1603775329 AND 1606280929
GROUP BY t1.company_short_name
Where I need to found all the company_short_name with the count of access, and if there is no access or the count is 0 then it should come COUNT(t2.user_ip_address) is 0. When I am not using where condition its working perfectly but after the use of where condition its giving only the result where the count is greater then 1. I have tried a lot but I am not able to modify the code. Any suggestions will be of great help
Put your where clause condition to ON clause
SELECT t1.company_short_name, COUNT(t2.user_ip_address) as chart_accessed
FROM tblcompanymaster t1
LEFT JOIN tblhistorymaster t2 ON t1.row_id = t2.company_id
and t2.user_last_request_time BETWEEN 1603775329 AND 1606280929
GROUP BY t1.company_short_name
You can add the filtering (where) component to the join instead - only taking the values if they exist in t2.
SELECT t1.company_short_name, COUNT(t2.user_ip_address) as chart_accessed
FROM tblcompanymaster t1
LEFT JOIN tblhistorymaster t2 ON t1.row_id = t2.company_id AND t2.user_last_request_time BETWEEN 1603775329 AND 1606280929
GROUP BY t1.company_short_name
I have a query like below. This query is working fine but since I have huge amount of data to check, this query running is slower.
Can anybody help me how to optimize this query?
SELECT * from trn where concat(comp_id,cus_id)
IN (select concat(comp_id,cus_id) FROM cus where sid='A0001')
AND docdate between ('2018-01-01') and ('2018-04-30')
The concat is probably causing those performance problems as it can't use indexes.
But MySQL supports multi-column subqueries, so simply remove it:
SELECT * from trn
where (comp_id,cus_id) IN
( select comp_id,cus_id
FROM cus
where sid='A0001'
)
AND docdate between ('2018-01-01') and ('2018-04-30')
You can use JOIN, e.g.:
SELECT DISTINCT t.*
FROM trn t
JOIN cus c ON t.comp_id = c.comp_id AND t.cus_id = c.cus_id
WHERE c.sid='A0001' AND t.docdate BETWEEN ('2018-01-01') AND ('2018-04-30');
You can use EXISTS :
SELECT t.*
FROM trn t
WHERE EXISTS (SELECT 1
FROM cus c
WHERE c.sid = 'A0001' AND c.comp_id = t.comp_id AND c.cus_id = t.cus_id
) AND
docdate between '2018-01-01' and '2018-04-30';
This is my Query I want to get latest record in each group.I have two table t_service_request and t_request_chkpoint
t_service_request
------------
LTS,JFT,CUS_NO,REQUETST_ID...
t_request_chkpoint
------------
LTS ,REQUETST_ID...
Both table match by REQUETST_ID.
I want to group by cus_no in table t_service_request
SELECT S.*, A.ID as CID, A.ENTRY_ID, A.LTS
FROM maintenance.t_service_request S
WHERE JFT IN (
SELECT MAX(JFT)
FROM maintenance.t_service_request
GROUP BY CUS_NO
) LEFT OUTER JOIN maintenance.t_request_chkpoint A
ON S.REQUEST_ID = A.REQUEST_ID where S.COMPANY_ID = '0002' AND S.STATE >= 3 AND A.STATE >= 3
but didn't work any suggestions ?
t_service_request
------------
LTS|JFT|CUS_NO|REQUETST_ID|
t_request_chkpoint
------------
|LTS|REQUETST_ID|
Join above two table(Request_id) and select latest JFT in each CUS_NO
Try this, maybe works;)
SELECT DISTINCT
S.*,
A.ID AS CID,
A.ENTRY_ID,
A.LTS
FROM maintenance.t_service_request S
LEFT JOIN maintenance.t_request_chkpoint A ON A.REQUETST_ID = S.REQUETST_ID AND A.STATE >= 3
WHERE S.JFT = (SELECT MAX(B.JFT)
FROM maintenance.t_service_request B
WHERE B.CUS_NO = S.CUS_NO
GROUP BY B.CUS_NO)
AND S.COMPANY_ID = '0002' AND S.STATE >= 3
I think your sql may have some syntax errors and I am not sure I've misunderstood your requirement or not.
I must admit, I still don't understand what you are asking. Your query, however, is incomplete, and maybe fixing it solves your problem already.
You say you want "to get latest record in each group" and in your query you are looking for the maximum JFT per CUS_NO. Then, however you are only comparing the JFT and not the CUS_NO.
Moreover, your query is syntactically incorrect, as it has two WHERE clauses. Last but not least, (outer) join criteria (state >= 3 here) belongs in the ON clause, not in the WHERE clause.
Here is the corrected query:
select
sr.*,
rc.id as cid,
rc.entry_id,
rc.lts
from maintenance.t_service_request sr
left outer join maintenance.t_request_chkpoint rc on rc.request_id = sr.request_id
and rc.state >= 3
where sr.company_id = '0002' and sr.state >= 3
and (sr.cus_no, sr.jft) in
(
select cus_no, max(jft)
from maintenance.t_service_request
group by cus_no
);
I have 3 tables: broadcasts, broadcasts_likes and broadcasts_viewers:
I want return result include total_likes, total_viewers but when I run this sql, the expectation is wrong, could you help me check this. I just want use sql normally, don't use sub query. Here is my sql:
SELECT `b`.*,
COUNT(`bl`.`broadcast_id`) AS `total_likes`,
COUNT(`bv`.`broadcast_id`) AS `total_viewers`
FROM `broadcasts` `b`
LEFT JOIN `broadcasts_likes` `bl`
ON `b`.`broadcast_id` = `bl`.`broadcast_id`
LEFT JOIN `broadcasts_viewers` `bv`
ON `b`.`broadcast_id` = `bv`.`broadcast_id`
GROUP BY `b`.`broadcast_id`;
The simplest solution is to switch to count(distinct):
SELECT `b`.*,
COUNT(DISTINCT `bl`.profile_id`) AS `total_likes`,
COUNT(DISTINCT `bv`.view_profile_id) AS `total_viewers`
FROM `broadcasts` `b` LEFT JOIN
`broadcasts_likes` `bl`
ON `b`.`broadcast_id` = `bl`.`broadcast_id` LEFT JOIN
`broadcasts_viewers` `bv`
ON `b`.`broadcast_id` = `bv`.`broadcast_id`
GROUP BY `b`.`broadcast_id`;
If broadcast have lots of views and lots of likes, this won't scale particularly well. In that case, you can aggregate the tables before joining or use correlated subqueries:
SELECT `b`.*,
(SELECT COUNT(*)
FROM broadcasts_likes bl
WHERE `b`.`broadcast_id` = `bl`.`broadcast_id`
) as `total_likes`,
(SELECT COUNT(*)
FROM broadcasts_viewers bv
WHERE `b`.`broadcast_id` = `bv`.`broadcast_id`
) as `total_viewers`
FROM `broadcasts` `b`;
Actually, with indexes on broadcasts_likes(broadcast_id) and broadcasts_viewers(broadcast_id), this very should have very good performance.
How do i combined this to two select query using left join syntax. (My query has error and I can't find a solution)
select
*
from
(select
mi.parent_entity_id entity,
tctp.institution_rec_id institutionRecId,
institution_code storecode,
institution_name storename,
case when sum(unsettled_points) is null
then coalesce (sum(point_value),0)
else coalesce
(sum(unsettled_points),0) end sumpoints
from
t_card_transaction_point tctp
inner join
m_institution mi on tctp.institution_rec_id=mi.institution_rec_id
where
mi.parent_entity_id = 70125 and
tctp.point_status = 'xy4604'
group by
entity,
institutionRecId,
storecode,
storename
) storeExpired
left join
entityExpired on storeExpired.entity=entityExpired.entity
(select
mpb.institution_rec_id entity,
tctd.institution_rec_id institutionRecId,
tctd.card_no cardnumber,
total_amount_primary totalpoints,
case when total_unsettled_points is null
then point_value
else tctd.total_unsettled_points end
points
from
t_card_transaction_detail tctd inner
join
m_point_bucket mpb on mpb.card_no=tctd.card_no
inner join
m_institution mi on mi.institution_rec_id=tctd.institution_rec_id
where
mpb.total_amount_primary > 1000 and
tctd.adjustment_date is null
group by
entity,
institutionRecId,
cardnumber,
totalpoints,
points
) entityExpired
Firstly:
We do appreciate proper indenting / lining of code for ease of readability :)
Second:
"My query has error" is not particularly explanatory.
Anywho, to answer your question:
SQL has an order of operation of
From
Where
Group By
Having
Select
Order By
This means that the alias are created when the select is executed. And since "group by" is executed before this, the alias's doesn't exist yet - this is probably the error you are getting.
Also, I'm not sure if MySQL does allow a join on a alias, which is defined further down in the query (I could be wrong though), so i would move the query itself into the join brackets, and use on the "on"-clause afterwards.
Sample query: (Not tested, since I doesn't have the tables)
select
*
from (
select
mi.parent_entity_id as entity
, tctp.institution_rec_id as institutionRecId
, institution_code as storecode
, institution_name as storename
, case when sum(unsettled_points) is null
then coalesce (sum(point_value),0)
else coalesce (sum(unsettled_points),0)
end as sumpoints
from t_card_transaction_point tctp
inner join m_institution mi on tctp.institution_rec_id = mi.institution_rec_id
where 1=1
and mi.parent_entity_id = 70125
and tctp.point_status = 'xy4604'
group by
mi.parent_entity_id
, tctp.institution_rec_id
, institution_code
, institution_name
) storeExpired
left join (
select
mpb.institution_rec_id as entity
, tctd.institution_rec_id as institutionRecId
, tctd.card_no as cardnumber
, total_amount_primary as totalpoints
, case when total_unsettled_points is null
then point_value
else tctd.total_unsettled_points
end as points
from t_card_transaction_detail tctd
inner join m_point_bucket mpb on mpb.card_no=tctd.card_no
inner join m_institution mi on mi.institution_rec_id=tctd.institution_rec_id
where 1=1
and mpb.total_amount_primary > 1000
and tctd.adjustment_date is null
group by
mpb.institution_rec_id
, tctd.institution_rec_id
, tctd.card_no
, total_amount_primary
, case when total_unsettled_points is null
then point_value
else tctd.total_unsettled_points
end
) entityExpired on storeExpired.entity=entityExpired.entity
Edit:
I just google'd it, and you can in fact use alias's in your group by statement in MySQL (Not allowed in MSSQL, nor is it ANSI standard).
However, after seeing your comment regarding the error, it is probably due to the fact that you are joining with the alias entityExpired, before the subquery is created. I'm guessing that moving the subquery, as I've done in the example, should work.