Combining Multiple SQL Queries Into Single Query - sql

I have three queries as below and I need to combine them into one. Does any body know how to do that?
$myTasks = "";
$query = "SELECT taskID_PK " .
"FROM tasks t " .
"LEFT JOIN task_assignee ta ON ta.taskID_FK = t.taskID_PK ".
"LEFT JOIN task_attachments a ON a.taskID_FK = t.taskID_PK ".
"LEFT JOIN employee e ON e.employeeID_PK = t.assignByID_FK ".
" WHERE TRUE AND isArchive != 1 AND taskStatus = 1 AND ta.clientID_FK = {$G_CLIENID} AND categoryID_FK !=0 group by taskID_PK ";
$RawData = db::select($query);
$myTasks= count($RawData);
$closeTasks = "";
$query = "SELECT taskID_PK,taskTitle,taskDescn,categoryID_FK,priority,date_format(createDate, '%d/%m/%Y') as createDate,ticketID_FK,
date_format(dueDate, '%d/%m/%Y') as dueDate ,assignByID_FK,createTime, taskStatus,closedDate,employeeName ,attachmentID_PK " .
"FROM tasks t " .
"LEFT JOIN task_assignee ta ON ta.taskID_FK = t.taskID_PK ".
"LEFT JOIN task_attachments a ON a.taskID_FK = t.taskID_PK ".
"LEFT JOIN employee e ON e.employeeID_PK = t.assignByID_FK ".
" WHERE TRUE AND isArchive != 1 AND (taskStatus != 1 ){$taskCreateClause} AND categoryID_FK !=0 group by taskID_PK ";
$RawData = db::select($query);
$closeTasks = count($RawData);
$workLoad ="";
$query = "SELECT taskID_PK,taskTitle,taskDescn,categoryID_FK,priority,date_format(createDate, '%m/%d/%Y') as createDate,ticketID_FK,
date_format(dueDate, '%m/%d/%Y') as dueDate ,assignByID_FK,createTime, taskStatus,closedDate,employeeName ,clientID_FK " .
"FROM task_assignee ta " .
"LEFT JOIN tasks t ON ta.taskID_FK = t.taskID_PK ".
"LEFT JOIN employee e ON e.employeeID_PK = ta.clientID_FK ".
" WHERE TRUE AND taskStatus = 1 ";
$RawData = db::select($query);
$workLoad = count($RawData);

Okay now that I understand the question, how about something like this:
select a.taskID_PK,
(Select count(*)) .
"FROM tasks t " .
"LEFT JOIN task_assignee ta ON ta.taskID_FK = t.taskID_PK ".
"LEFT JOIN task_attachments a ON a.taskID_FK = t.taskID_PK ".
"LEFT JOIN employee e ON e.employeeID_PK = t.assignByID_FK ".
" WHERE TRUE AND isArchive != 1 AND taskStatus = 1 AND ta.clientID_FK = {$G_CLIENID} AND categoryID_FK !=0
and task_ID_PK = a.taskID_PK) as Count1,
group by taskID_PK
....
from tasks
Select the main ID, then 3 independent select statements return a count and joined up with the ID at the beginning.

SELECT
(SELECT(COUNT(DISTINCT t.taskID_PK))
FROM tasks t
LEFT JOIN task_assignee ta ON ta.taskID_FK = t.taskID_PK
LEFT JOIN task_attachments a ON a.taskID_FK = t.taskID_PK
LEFT JOIN employee e ON e.employeeID_PK = t.assignByID_FK
WHERE TRUE AND isArchive != 1 AND taskStatus = 1 AND categoryID_FK !=0)as activetasks,
(SELECT(COUNT(DISTINCT t.taskID_PK))
FROM tasks t
LEFT JOIN task_assignee ta ON ta.taskID_FK = t.taskID_PK
LEFT JOIN employee e ON e.employeeID_PK = t.assignByID_FK
WHERE TRUE AND isArchive != 1 AND taskStatus = 1 AND ta.clientID_FK=1 AND categoryID_FK !=0)as mytasks,
(SELECT(COUNT(DISTINCT t.taskID_PK))
FROM tasks t
LEFT JOIN task_assignee ta ON ta.taskID_FK = t.taskID_PK
LEFT JOIN employee e ON e.employeeID_PK = t.assignByID_FK
WHERE TRUE AND isArchive != 1 AND taskStatus != 1 AND categoryID_FK !=0)as cloastasks,
(SELECT(COUNT(t.taskID_PK))
FROM task_assignee ta
LEFT JOIN tasks t ON ta.taskID_FK = t.taskID_PK
LEFT JOIN employee e ON e.employeeID_PK = ta.clientID_FK
WHERE TRUE AND taskStatus = 1)as workload,
(SELECT(COUNT(DISTINCT t.taskID_PK))
FROM tasks t
LEFT JOIN task_assignee ta ON ta.taskID_FK = t.taskID_PK
LEFT JOIN task_attachments a ON a.taskID_FK = t.taskID_PK
LEFT JOIN employee e ON e.employeeID_PK = t.assignByID_FK
WHERE TRUE AND isArchive = 1 AND categoryID_FK !=0)as archivetasks.
I combined my queries and I want to know is there any better way to combine those to improve efficiency?

Related

Postgres Left Join ignores row if ManyToOne property is null

In Spring Boot i have the following query in a PostgreSQL database, to get data from ConfigElement table and set them to the new one ConfigurationReview table. It works properly as expected:
#Query(
"SELECT new xx.xx.xx.dao.ConfigurationReview(r.id, MAX(ce.id) AS configElementId,"
+ " r.checkMethod, r.targetDate, r.endDate, r.sessionDate, SUM(CASE WHEN i.criticality ="
+ " 0 AND i.relation = 0 THEN 1 ELSE 0 END) AS majorFindings, SUM(CASE WHEN i.criticality"
+ " = 1 AND i.relation = 0 THEN 1 ELSE 0 END) AS minorFindings, r.state) FROM"
+ " ConfigElement ce "
+ "LEFT JOIN ce.reviews r ON r.configElement.id = ce.id "
+ "LEFT JOIN r.criteria cr ON cr.review.id = r.id "
+ "LEFT JOIN cr.issues i ON i.criterion.id = cr.id "
+ "WHERE ce.id = :configurationId AND r.id IS NOT NULL GROUP BY r.id")
Page<ConfigurationReview> findConfigurationReviews(
#Param("configurationId") Long configurationId, Pageable pageable);
There was a need to add another property (r.milestone) with a ManyToOne relation, so i added it to the query:
#Query(
"SELECT new xx.xx.xx.dao.ConfigurationReview(r.id, MAX(ce.id) AS configElementId,"
+ " r.checkMethod, r.targetDate, r.endDate, r.sessionDate, SUM(CASE WHEN i.criticality ="
+ " 0 AND i.relation = 0 THEN 1 ELSE 0 END) AS majorFindings, SUM(CASE WHEN i.criticality"
+ " = 1 AND i.relation = 0 THEN 1 ELSE 0 END) AS minorFindings, r.state, r.milestone) FROM"
+ " ConfigElement ce "
+ "LEFT JOIN ce.reviews r ON r.configElement.id = ce.id "
+ "LEFT JOIN r.criteria cr ON cr.review.id = r.id "
+ "LEFT JOIN cr.issues i ON i.criterion.id = cr.id "
+ "WHERE ce.id = :configurationId AND r.id IS NOT NULL GROUP BY r.id")
Page<ConfigurationReview> findConfigurationReviews(
#Param("configurationId") Long configurationId, Pageable pageable);
Here is the milestone entry in ConfigurationReview dao:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(foreignKey = #ForeignKey(name = "fk_review_milestones_on_milestone_id"))
private Milestone milestone;
With the above changes, it works properly if r.milestone is not null. But when the r.milestone is null, the complete row is ignored in left join.
As a result, if I have 2 r.milestones with data and 2 r.milestones without, the above query returns only two entries instead of four.
The problem appears only if r.milestone is null (because of the ManyToOne relation?). If another property is null, the row is returned properly.
Any idea how can I fix this?

I have A problem with dividing the value of 0 by 0 in an Access database

When I try to extract the result of Division 2 Field from table in access database
If I have a value of 0 an error occurs
sqlSTR = "SELECT TBL_Category_Item_File.Item_Org_Price2/TBL_Stocks_Balances.Item_QTY AS ['Price']FROM (((TBL_Category_Item_File INNER JOIN TBL_Suppliers_Product ON TBL_Category_Item_File.Item_ID = TBL_Suppliers_Product.Item_ID) INNER JOIN TBL_Suppliers ON TBL_Suppliers_Product.Supp_ID = TBL_Suppliers.Supp_ID) INNER JOIN TBL_Sub_categories ON TBL_Category_Item_File.ID_Sub_categories = TBL_Sub_categories.ID_Sub_categories) INNER JOIN TBL_Stocks_Balances ON (TBL_Stocks_Balances.Item_ID = TBL_Category_Item_File.Item_ID) AND (TBL_Category_Item_File.Item_BarCode = TBL_Stocks_Balances.Item_Barcode) WHERE tbl_Category_Item_File.Catg_ID =" & Split(cmblist.Text, " - ")(0)
If you are trying to avoid the error, you can use a CASE statement in your query to check for a 0 value in the Item_Org_Price2 field and return a different value if it is 0. For example, you could do something like this:
SELECT
CASE
WHEN TBL_Category_Item_File.Item_Org_Price2 = 0
THEN 0
ELSE TBL_Category_Item_File.Item_Org_Price2/TBL_Stocks_Balances.Item_QTY
END AS ['Price']
FROM (((TBL_Category_Item_File INNER JOIN TBL_Suppliers_Product ON TBL_Category_Item_File.Item_ID = TBL_Suppliers_Product.Item_ID) INNER JOIN TBL_Suppliers ON TBL_Suppliers_Product.Supp_ID = TBL_Suppliers.Supp_ID) INNER JOIN TBL_Sub_categories ON TBL_Category_Item_File.ID_Sub_categories = TBL_Sub_categories.ID_Sub_categories) INNER JOIN TBL_Stocks_Balances ON (TBL_Stocks_Balances.Item_ID = TBL_Category_Item_File.Item_ID) AND (TBL_Category_Item_File.Item_BarCode = TBL_Stocks_Balances.Item_Barcode) WHERE tbl_Category_Item_File.Catg_ID =" & Split(cmblist.Text, " - ")(0)

SQL query for select statement when certain bind parameters were entered

I need help with a select statement. I want to use this for my search API where if you pass in certain parameters, fist Name, or last Name, or both, or first Name and state, the query will run as other parameters were not filled it.
Is there a way to do that? This is my query
select d.is_purged, d.is_reorg, ds.dlr_nm, ds.city, c.first_nm, c.middle_nm,
c.last_nm, c.is_mdd, ds.state, lds.display_name, c.is_wrn, d.crt_ts, d.upd_ts
from deal d
left join candidate c on d.candidate_id = c.id
left join lkup_deal_status lds on d.status = lds.status
left join dealership ds on d.id = ds.deal_id
where (c.first_nm is null or c.first_nm = :firstName )
and (d.is_purged = false )
and (ds.dlr_nm is null or ds.dlr_nm = :dealershipName)
and (ds.city is null or ds.city = :city)
and (c.middle_nm is null or c.middle_nm = :middleName)
and (c.last_nm is null or c.last_nm = :lastName)
and (ds.state is null or ds.state = :state)
and (lds.display_name is null or lds.display_name = :status)
thanks in advance
I ended up figuing it out.
For Java: String SEARCH_DEAL = "select d.id, ds.id, ds.dlr_nm, d.bac,
d.is_reorg, c
c.first_nm, c.middle_nm, " +
"c.last_nm, c.is_mdd, c.is_wrn, ds.city, ds.state, ds.rgn,
lds.display_name, d.crt_ts, d.upd_ts " +
"from mhdid_171749.deal d left join candidate c on d.candidate_id = c.id
" +
"left join lkup_deal_status lds on d.status = lds.status " +
"left join dealership ds on d.id = ds.deal_id " +
"where d.is_purged = false " +
" and (:dealershipName::varchar is null or ds.dlr_nm = :dealershipName)"
+
" and (:firstName::varchar is null or c.first_nm = :firstName ) " +
" and (:lastName::varchar is null or c.last_nm = :lastName) " +
" and (:bacCode::int is null or d.bac = :bacCode)" +
" and (:city::varchar is null or ds.city = :city) " +
" and (:state::varchar is null or ds.state = :state) " +
" and (:region::varchar is null or ds.rgn = :region) " +
" and (:status::varchar is null or lds.display_name = :status) ";
For SQL:
select d.is_purged, d.is_reorg, ds.dlr_nm, ds.city, c.first_nm,
c.middle_nm,
c.last_nm, c.is_mdd, ds.state, lds.display_name, c.is_wrn, d.crt_ts,
d.upd_ts
from mhdid_171749.deal d
left join candidate c on d.candidate_id = c.id
left join lkup_deal_status lds on d.status = lds.status
left join dealership ds on d.id = ds.deal_id
where d.is_purged = false
and (:firstName is null or c.first_nm = :firstName )
and (:dealershipName is null or ds.dlr_nm = :dealershipName)
and (:city is null or ds.city = :city)
and (:middleName is null or c.middle_nm = :middleName)
and (:lastName is null or c.last_nm = :lastName)
and (:state is null or ds.state = :state)
and (:status is null or lds.display_name = :status);

Unable to convert SQL to JPQL

I am trying to convert following Oracle SQL (which works)
select sum(ct.some_count) from TABLE1 mc
inner join TABLE2 xref on mc.cnum = xref.cnum
inner join TABLE3 ct on xref.srt = ct.srt
inner join TABLE4 pc on pc.id = xref.id
where mc.CARD_NO = '111' and pc.code = '222';
To following JPQL.
#Query("SELECT sum(ct.someCount) FROM Table1Entity mc " +
"inner join TABLE2Entity xref on mc.cnum = xref.cnum " +
"inner join TABLE3Entity ct on xref.srt = ct.srt " +
"inner join TABLE4Entity pc on pc.id = xref.id " +
"where mc.CARD_NO = :cardNumber and pc.code = :code")
long getTotalCount(#Param("cardNumber") String cardNumber, #Param("code") String code);
I am getting the following Exception.
QuerySyntaxException: unexpected token
Can I please get some help on what I am doing wrong?
I am using Spring and this is my Repository for this Query.
#Repository(value = "someCountRepository")
public interface SomeCountRepository extends JpaRepository<Table3Entity, TableId> {
#Query("SELECT sum(ct.someCount) FROM Table1Entity mc " +
"inner join TABLE2Entity xref on mc.cnum = xref.cnum " +
"inner join TABLE3Entity ct on xref.srt = ct.srt " +
"inner join TABLE4Entity pc on pc.id = xref.id " +
"where mc.CARD_NO = :cardNumber and pc.code = :code")
long getTotalCount(#Param("cardNumber") String cardNumber, #Param("code") String code);
}
#Query("SELECT sum(ct.someCount) FROM Table1Entity mc " +
"inner join TABLE2Entity xref on mc.cnum = xref.cnum " +
"inner join TABLE3Entity ct on xref.srt = ct.srt " +
"inner join TABLE4Entity pc on pc.id = xref.id " +
"where mc.CARD_NO = :cardNumber and pc.code = :code",
nativeQuery = true) // set native query to true
long getTotalCount(#Param("cardNumber") String cardNumber, #Param("code") String code);
Since you are copy the query exactly from Oracle SQL which is not JPQL, then you should declare it as native query.
References : Spring Data JPA #Query #2.2. Native

Access 2003 SQL Syntax error

I am new with access 2003 and been stuck on this query I have wrote for a while now. The tables and column names, operators and brackets i believe are all correct however I am getting a syntax error only after I inserted the following join operation
FROM (tDailyEntries
INNER JOIN tLEDGERS ON tLEDGERS.Action = tDailyEntries.ActionNo)
INNER JOIN (tProjects
below is my full code
SELECT DISTINCT tProjects.CC_IO AS ProjectNo,
Year([DateFrom]) & " Accrual " & MonthName(Month([DateFrom])) & " - "+[CompanyName] & " ( "+([LastName]) & ")" AS [Line/Item/Text],
tUsers.LastName AS Last_Name,
tDailyEntries.UserId AS UserID,
contractordailyrate AS DailyRate,
contractordailyhours AS Hours,
ROUND(contractordailyrate / contractordailyhours, 2) AS HourlyRate,
ROUND(SUM(tDailyEntries.CalculatedDailyHours), 2) AS MonthlyHours,
ROUND((HourlyRate * MonthlyHours), 2) AS Charge,
ROUND(Charge+ROUND((Charge*0.2),2),2) AS Accruals, tProjects.Project AS Project
FROM (tDailyEntries
INNER JOIN tLEDGERS ON tLEDGERS.Action = tDailyEntries.ActionNo)
INNER JOIN (tProjects
RIGHT JOIN (textcontractor
RIGHT JOIN (tTitle
RIGHT JOIN ((Location
RIGHT JOIN (tDepartments
RIGHT JOIN tUsers
ON tProjectType.ProjectTypeID = tProjects.ProjectTypeID)
ON tDepartments.DeptID = tUsers.DeptID)
ON tLocation.LocationID = tUsers.LocationID)
RIGHT JOIN (((tDailyEntries
LEFT JOIN tDepartments AS tDepartments_1
ON tDailyEntries.DeptCharged = tDepartments_1.DeptShortName)
LEFT JOIN tActions ON tDailyEntries.ActionNo = tActions.ActionID)
LEFT JOIN tLookups
ON tDailyEntries.Zone = tLookups.LookupID)
ON tUsers.UserID = tDailyEntries.UserID)
LEFT JOIN textmain
ON tUsers.UserID = textmain.userID)
ON tTitle.TitleID = tUsers.TitleID)
ON textcontractor.companyid = textmain.contractorcompany)
ON tProjects.ProjectID = tDailyEntries.ProjectNo
WHERE tTitle.TitleID = 37
AND Month([DateFrom]) = MonthNum
AND Day([DateFrom]) <21
GROUP BY tProjects.CC_IO, Year([DateFrom]) & " Accrual " & MonthName(Month([DateFrom])) & " - "+[CompanyName] & " ( "+([LastName]) & ")", tUsers.LastName, tDailyEntries.UserId, textmain.contractordailyrate,
Month([DateFrom]), textmain.contractordailyhours, tProjects.Project;
Any help would be great.