SQL Combining Two Totally seperate tables to one - sql

I am VERY new to SQL and self taught. I have two SQL that I stuggled through but got working. Now I need to combine them into one and I'm lost.
SELECT
s.lastfirst,
s.student_number,
SUM(tr.howmany)
FROM
students s
JOIN
truancies tr ON s.id = tr.studentid
WHERE
s.enroll_status = 0 AND
s.schoolid = ~(curschoolid)
GROUP BY
s.lastfirst, s.student_number
HAVING
SUM(tr.howmany) > 0
ORDER BY
s.lastfirst
And this table:
SELECT
S.DCID as DCID,
S.LASTFIRST as LASTFIRST,
S.STUDENT_NUMBER as STUDENT_NUMBER,
S2.FC_SRVC_HRS_DUE as FC_SRVC_HRS_DUE,
CASE
WHEN S2.FC_SRVC_HRS_COMPLETED IS NULL
THEN '0'
ELSE S2.FC_SRVC_HRS_COMPLETED
END AS FC_SRVC_HRS_COMPLETED,
S2.FC_SRVC_HRS_BUYOUT as FC_SRVC_HRS_BUYOUT,
CASE
WHEN S2.FC_SRVC_HRS_COMPLETED IS NULL
THEN S2.FC_SRVC_HRS_DUE * S2.FC_SRVC_HRS_BUYOUT
ELSE ((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT)
END as Balance_Due
FROM
STUDENTS S, U_STUDENTSUSERFIELDS S2
WHERE
S.DCID = S2.STUDENTSDCID AND
s.enroll_status = 0 AND
s.schoolid = ~(curschoolid) AND
(((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT) > 0 OR
((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT) IS NULL) AND
S2.FC_SRVC_HRS_DUE >.1
ORDER BY
s.lastfirst
What I am really looking for are the totals of both of these. I want the SUM(tr.howmany) from the first table and the balance due of the second BUT I need the filters that are in there. This would be sorted by student. I hope I am making sense. Any assistance would be appreciated.

You can join together 2 separate SQL select statements:
Eg:
Select A.id, A.value, B.value
From (select id, count(*) as value from TableA ...) AS A
join (select id, sum(field) as value from TableB ...) AS B
on A.id = B.id
order by A.id
As long as you have a common field to join on this would work. In your case the student_number looks like a good candidate. You will have to do the ordering outside of your subqueries.

Related

Case statement in multiple conditions?

I want to check the column mr.name, if mr.name is null then i have to replace mr.name as mr.ticket_no. How? Can use if else or case?
select ROW_NUMBER() OVER(ORDER BY mr_user) sl_no,* from (select
mr.name as mr_no,
coalesce(mr.user_id,0) as mr_user
from stock_production_lot lot
left join kg_grn grn on (grn.name = lot.grn_no)
left join kg_department_indent mr on (mr.name = grn.mr_no)
order by mr.user_id) main
where mr_user=65
When i use like this
case when mr.name is null then '' else mr.ticket_no = grn.mr_no as mr_no
it will throw an error
if mr.name = null means i have to replace mr.name = mr.ticket_no. I want to check the column mr.name, if mr.name is null then i have to replace mr.name as mr.ticket_no
You can use coalesce() to replace null with anything:
select ROW_NUMBER() OVER(ORDER BY mr_user) sl_no,* from (select
coalesce(mr.name,mr.ticket_no) as mr_no,
coalesce(mr.user_id,0) as mr_user
from stock_production_lot lot
left join kg_grn grn on (grn.name = lot.grn_no)
left join kg_department_indent mr on (mr.name = grn.mr_no)
order by mr.user_id) main
where mr_user=65
But if you are comfortable with case when then use as below:
select ROW_NUMBER() OVER(ORDER BY mr_user) sl_no,* from (select
(case when mr.name is null then mr.ticket_no else mr.name end) as mr_no,
coalesce(mr.user_id,0) as mr_user
from stock_production_lot lot
left join kg_grn grn on (grn.name = lot.grn_no)
left join kg_department_indent mr on (mr.name = grn.mr_no)
order by mr.user_id) main
where mr_user=65

Subquery returned more than 1 value - MS SQL

select Id,Prayaseeid, name,Gender,
(select name from tb_Category where id = Category) AS Category,
ideadescription,Domain,ProjectTerms,ProjectStartDate,Amountsanctioned,
(select Amount from tb_innovatorDisbursement where tbid ='TBINO1111A' and
applyingforcycle='1') AS AmountDisbursed,
projectstatus,projectoutcome
from tb_innovator
where tbid='TBINO1111A 'and applyingforcycle='1'
Use TOP to Limit rows to 1,
The Select queries in parenthesis resulting in more than one record
select Id,Prayaseeid, name,Gender,
(select TOP(1) name from tb_Category where id = Category) AS Category,
ideadescription,Domain,ProjectTerms,ProjectStartDate,Amountsanctioned,
(select TOP(1) Amount
from tb_innovatorDisbursement where tbid ='TBINO1111A' and applyingforcycle='1') AS AmountDisbursed,
projectstatus,projectoutcome from tb_innovator
where tbid='TBINO1111A 'and applyingforcycle='1'
You need to test your sub queries for the where clause to make sure the values you are searching do not have multiple records. I would use (Top 1 ) for any column other than the Id column assuming the Id column must be unique as the name suggests.
Update query
select ti.Id,
ti.Prayaseeid,
ti.name,
ti.Gender,
(select TOP(1) name from tb_Category where id = ti.Category) AS Category,
ti.ideadescription,
ti.Domain,
ti.ProjectTerms,
ti.ProjectStartDate,
ti.Amountsanctioned,
tid.Amount AS AmountDisbursed,
ti.projectstatus,
ti.projectoutcome
from tb_innovator ti
INNER JOIN tb_innovatorDisbursement tid ON tid.Tbid = ti.tbid
AND tid.applyingforcycle='1'
where ti.tbid='TBINO1111A 'and ti.applyingforcycle='1'
Perhaps you should use JOIN:
select i.Id, i.Prayaseeid, i.name, i.Gender, c.Category,
i.ideadescription, i.Domain, i.ProjectTerms, i.ProjectStartDate, i.Amountsanctioned,
id.Amount from tb_innovatorDisbursement
i.projectstatus, i.projectoutcome
from tb_innovator i left join
tb_Category c
on i.category = c.id left join
tb_innovatorDisbursement id
on id.tbid = i.dbid and id.applyingforcycle = '1'
where i.tbid = 'TBINO1111A 'and i.applyingforcycle = '1';
Note that all column names are qualified as well, indicating what table they come from.

Return a Count of 0 When No Rows

OK, I've looked this up and tried a number of solutions, but can't get it to work. I'm a bit of a novice. Here's my original query - how can I get it to return 0 for an account when there are no results in the student table?
SELECT a.NAME
,count(s.student_sid)
FROM account a
JOIN inst i ON a.inst_sid = i.root_inst_sid
JOIN inst_year iy ON i.inst_sid = iy.inst_sid
JOIN student s ON iy.inst_year_sid = s.inst_year_sid
WHERE s.demo = 0
AND s.STATE = 1
AND i.STATE = 1
AND iy.year_sid = 16
AND a.account_sid IN (
20187987
,20188576
,20188755
,52317128
,20189249
)
GROUP BY a.NAME;
Use an outer join, moving the condition on that table into the join:
select a.name, count(s.student_sid)
from account a
join inst i on a.inst_sid = i.root_inst_sid
join inst_year iy on i.inst_sid = iy.inst_sid
left join student s on iy.inst_year_sid = s.inst_year_sid
and s.demo = 0
and s.state = 1
where i.state = 1
and iy.year_sid = 16
and a.account_sid in (20187987, 20188576, 20188755, 52317128, 20189249)
group by a.name;
count() does not count null values, which s.student_sid will be if no rows join from student.
You need to LEFT JOIN and then SUM() over the group where s.student_sid is not null:
select
a.name,
sum(case when s.student_sid is null then 0 else 1 end) as student_count
from account a
join inst i on a.inst_sid = i.root_inst_sid
join inst_year iy on i.inst_sid = iy.inst_sid
left join student s
on iy.inst_year_sid = s.inst_year_sid
and s.demo = 0
and s.state = 1
where i.state = 1
and iy.year_sid = 16
and a.account_sid in (20187987, 20188576, 20188755, 52317128, 20189249)
group by a.name;
This is assuming that all of the fields in the student table that you are filtering on are optional. If you don't want to enforce removal of records where, say, s.state does not equal 1, then you need to move the s.state=1 predicate into the WHERE clauses.
If, for some reason, you are getting duplicate student IDs and students are being counted twice, then you can change the aggregate function to this:
count(distinct s.student_id) as student_count
...which is safe to do as count(distinct ...) ignores null values.

How to use a sum (case) into second table as condition

This is my query:
select matricule,nom_ligne,count(num_ticket) as nbre_ticket, sum(prix) as moant,receveur, nom_gie,
(SELECT SUM(CASE WHEN depense.id_bus = 1 THEN depense.montant ELSE 0 END) AS NbrARRNP from depense) as tot,
receveur, nom_gie from journal_recettes
group by matricule,nom_ligne,receveur, nom_gie
And I obtain this results:
Results
But what I need is to use this condition :
CASE WHEN depense.id_bus = journal_recettes.id_bus THEN depense.montant ELSE 0 END
But When I try, i obtain this error :
Error
Consider modifying your query like below by joining both tables on id_bus column
select j.matricule,
j.nom_ligne,
count(j.num_ticket) as nbre_ticket,
sum(j.prix) as moant,
j.receveur,
j.nom_gie,
SUM(d.id_bus) AS NbrARRNP
from journal_recettes j
join depense d on d.id_bus = j.id_bus
group by j.matricule,
j.nom_ligne,
j.receveur,
j.nom_gie;
You are looking for a correlated subquery. This is usually handled in the where clause:
select matricule, nom_ligne, count(num_ticket) as nbre_ticket,
sum(prix) as moant, receveur, nom_gie,
(select SUM(d.montant) AS NbrARRNP
from depense d
where d.id_bus = jr.id_bus
) as tot,
receveur, nom_gie
from journal_recettes jr
group by matricule, nom_ligne, receveur, nom_gie;
In this case, you may have an issue because the correlation condition is not a group by key. I'm not sure if Postgres supports this construct. If this is a problem, the simplest solution is to include id_bus in the group by, but without sample data, I'm not sure if that works in this case.
Assuming you are doing the join on id_bus, you can use Common Table Expressions (http://www.postgresql.org/docs/9.5/static/queries-with.html)
with sums as (SELECT id_bus, sum(CASE
WHEN depense.id_bus = 1 THEN depense.montant
ELSE 0
END) AS NbrARRNP
FROM depense
group by id_bus)
SELECT matricule,
nom_ligne,
Count(num_ticket) AS nbre_ticket,
Sum(prix) AS moant,
receveur,
nom_gie,
d.NbrARRNP AS tot,
receveur,
nom_gie
FROM journal_recettes j left outer join sums d on j.id_bus = d.id_bus
GROUP BY matricule,
nom_ligne,
receveur,
nom_gie,
j.id_bus
Many thanks to all.
I post my final solution to contribute :
select p1.matricule,p1.nom_ligne,
Count(p1.num_ticket) as nbre_ticket, Sum(p1.prix) as montant,
(select sum(montant) as tot from depense p2
where date_trunc('day',p2.date_depense) = date_trunc('day',p1.date_vendu)
group by date_depense) som_depense ,
(Sum(p1.prix) -((select sum(montant) as tot from depense p3
where date_trunc('day',p3.date_depense) = date_trunc('day',p1.date_vendu)
group by date_depense) ) ) net_reverse ,to_char(p1.date_vendu,'YYYYMMDD'),
p1.receveur, p1.nom_gie, id_line
from journal_recettes p1
group by
matricule,nom_ligne, date_vendu,receveur,nom_gie, id_line
And it's work as well.

Find duplicates in SQL Server database where one of the columns must differ

I'm trying to write a SQL query to find duplicates. What I can't manage to do is to make my query only select duplicates where one of the columns value must differ. So, I want to find all the duplicates where all the columns are the same, but one of the values must differ.
What I've got at the moment:
SELECT
a.1, underlag.1, f.1, f.2, f.3, f.4, f.5, f.6, f.7, f.8,
COUNT(*) TotalCount
FROM
f
JOIN
a ON a.Id = f.Id
JOIN
underlag ON underlag.Id = f.Id
GROUP BY
a.1, underlag.1, f.1, f.2, f.3, f.4, f.5, f.6, f.7, f.8
HAVING
COUNT(*) > 1
ORDER BY
underlag.1
The column that I want to differ is f.9 but I've no clue on how to do this. Any help or pointers in the right direction would be great!
SELECT *
FROM (
SELECT
a1 = a.[1]
, underlag1 = underlag.[1]
, f.[1], f.[2], f.[3], f.[4], f.[5], f.[6], f.[7], f.[8], f.[9]
, val = SUM(1) OVER (PARTITION BY CHECKSUM(f.[1], f.[2], f.[3], f.[4], f.[5], f.[6], f.[7], f.[8]))
FROM f
JOIN a on a.Id = f.Id
JOIN underlag on underlag.Id = f.Id
) t
WHERE t.val > 1
ORDER BY underlag1