Selecting Same Column Twice Using Alias Table - sql

Below are examples of the tables I am working with. These only represent the columns relevant to my query
_Requirements
RequirementID fkOwningWsID
-------------------------------------------
REQ-RPT-01 1
REQ-RPT-02 2
_Workstream
pk WsNm
-------------------------------------------
1 Workstream1
2 Workstream2
mnWorkstream_Leads
fkWsID fkEeID
-------------------------------------------
1 1
1 2
2 1
2 2
The below table is a result of a union. Employees can be from different companies, the below union lists all the employee IDs, the IDs for the employees who are from Company 1 (0 otherwise) and IDs for employees from company 2 (0 otherwise)
qryTrackerAllEeList
EeID Company1_ID Company2_ID
-------------------------------------------
1 1 0
2 0 2
I am attempting to view the following result
RequirementID WsNm Company1_Lead Company2_Lead
--------------------------------------------------------------------
REQ-RPT-01 Workstream1 1 2
REQ-RPT-02 Workstream2 1 2
I have issued the following SQL
SELECT DISTINCT Req.RequirementID, Ws.Wsnm, company1_id.ee_id, company2_id.ee_id
FROM (((([_Requirements] AS Req
INNER JOIN [_Workstream] AS Ws ON Req.fkOwningWsID = Ws.pkWsID)
INNER JOIN [mnWorkstream_Leads] AS wsLeads ON Ws.pkWsID = wsLeads.fkWsID)
LEFT OUTER JOIN qryTrackerAllEeList AS company1 ON wsLeads.fkEeID = company1.Company1_ID)
LEFT OUTER JOIN qryTrackerAllEeList AS company2 ON wsLeads.fkEeID = company2.Company2_ID)
The issue is, however, that I retrieve the following results
RequirementID WsNm Company1_Lead Company2_Lead
--------------------------------------------------------------------
REQ-RPT-01 Workstream1 2
REQ-RPT-01 Workstream1 1
REQ-RPT-02 Workstream2 2
REQ-RPT-02 Workstream2 1
Any suggestions on how to eliminate these duplicative rows and null values?

Use MAX() and GROUP BY to only select the non null values and group them into one row:
SELECT DISTINCT Req.RequirementID, Ws.Wsnm,
MAX(company1_id.ee_id) as Company1_Lead, MAX(company2_id.ee_id) as Company2_Lead,
FROM (((([_Requirements] AS Req
INNER JOIN [_Workstream] AS Ws ON Req.fkOwningWsID = Ws.pkWsID)
INNER JOIN [mnWorkstream_Leads] AS wsLeads ON Ws.pkWsID = wsLeads.fkWsID)
LEFT OUTER JOIN qryTrackerAllEeList AS company1 ON wsLeads.fkEeID = company1.Company1_ID)
LEFT OUTER JOIN qryTrackerAllEeList AS company2 ON wsLeads.fkEeID = company2.Company2_ID)
GROUP BY req.RequirementID, Ws.Wsnm

Related

SQL split one column into two columns based on values and use columns

Table: ProductionOrder
Id Ordernumber Lotsize
1 Order1 50
2 Order 2 75
3 WO-order1 1
4 WO-order2 1
Table: history
Id ProductionOrderID Completed
1 3 1
2 3 1
3 4 1
4 4 1
Table: ProductionOrderDetail
ID ProductionOrderID ProductionOrderDetailDefID Content
1 1 16 50
2 1 17 7-1-2018
3 2 16 75
4 2 17 7-6-2018
Start of my code:
Select p.ID, p.OrderNumber,
Case productionOrderDetailDefID
Where(Select pd1.productionOrderDetailDefID where ProductionOrderDetialDefID = 16) then min(pd1.content)
from ProductionOrder p
Left join History h1 on p.id = h1.productionOrderID
Left Join ProductionOrderDetail pd1 on p.ID = ProductionOrderID
The result in trying to get is
Id Ordernumber Lotsize Productionorder Completed
1 Order1 50 WO-order1 2
2 Order 2 75 WO-order2 2
Any help would be appreciated.
Try this
SELECT ordernumber,lotsize,Ordernumber,count(Ordernumberid)
FROM productionorder inner join history on productionorder.id = history.Ordernumberid
GROUP BY Ordernumber;
A bit of weird joins going on here. You should add this to a SQL fiddle so that we can see our work easier.
A link to SQL fiddle: http://sqlfiddle.com/
Here is my first attempt
SELECT
po.id
, po.ordernumber
, po.lotsize
, po2.productionorder
, SUM(h.completed)
FROM productionorder as po
INNER JOIN history as h
ON h.id = po.id
INNER JOIN prodcuctionorder as po2
ON po2.ordernumberid = h.ordernumberid
WHERE po.id NOT EXISTS IN ( SELECT ordernumberid FROM history )
GROUP BY
po.id
, po.ordernumber
, po.lotzise
, po2.productionorder
How far does that get you?

SQL- Add Missing data in Left outer joing query

I have following data
Components
componentid title
1 houseRent
2 medical
3 Travelling Allowance
empPayrollMaster
MasterID EmployeeID SalaryMonthID
1 101 1
2 102 1
3 103 1
empPayrollDetail
DetailID MasterID ComponentID amount
1 1 1 100
2 1 2 500
3 2 1 300
4 2 3 250
5 3 1 150
6 3 2 350
7 3 3 450
Required Output
EmployeeID MasterID ComponentID amount
101 1 1 100
101 1 2 500
101 1 3 0
102 2 1 300
102 1 2 0
102 2 3 250
103 3 1 150
103 3 2 350
103 3 3 450
To get the required output if i do left outer join between components and empPayrollDetail I get null in EmployeeID and MasterID and amount Columns. How to modify left join to get the required output
You need to do a CROSS JOIN on Components and empPayrollMaster to generate first all combination of employees and components. Then, do a LEFT JOIN on empPayrollDetail to achieve the result, using ISNULL(amount, 0) for NULL amounts.
SQL Fiddle
SELECT
epm.EmployeeID,
epm.MasterID,
c.ComponentID,
amount = ISNULL(epd.amount, 0)
FROM empPayrollMaster epm
CROSS JOIN Components c
LEFT JOIN empPayrollDetail epd
ON epd.MasterID = epm.MasterID
AND epd.ComponentID = c.ComponentID
Try this
select empPayrollMaster.EmployeeID,empPayrollMaster.MasterID,
Components.componentid,isnull(empPayrollDetail.amount,0)
from empPayrollMaster
left join Components
on empPayrollMaster.EmployeeID is not null
left join empPayrollDetail
on empPayrollDetail.MasterID = empPayrollMaster.MasterID
and empPayrollDetail.ComponentID = Components.componentid
Try this way
select c.EmployeeID,d.MasterID,c.ComponentID,isnull(d.amount,0) as amount from (
select * from Components a
Cross join empPayrollMaster b) c
left outer join empPayrollDetail d on d.componentid =c.componentid
As you want the component amount for each employee in the master table you should use a insull(payrole_detail.amount,0) or, as #Turophile pointed out, the SQL standard function coalesce(payrole_detail.amount,0) for the amounts column.
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

query regarding joining of two tables

Suppose I have 2 below tables
sql> select * from fraud_types ;
fraud_id fraud_name
-------- ----------
1 Fraud 1
2 Fraud 2
3 Fraud 3
4 Fraud 4
5 Fraud 5
sql> select * from alarms ;
fraud_id dealer count
-------- ------ -----
1 Deal 1 5
3 Deal 1 3
5 Deal 1 4
1 Deal 2 2
2 Deal 2 6
3 Deal 2 1
4 Deal 2 7
5 Deal 2 9
I want to join the two tables and get the output as
dealer fraud_id count
------ -------- -----
Deal 1 1 5
Deal 1 2 0
Deal 1 3 3
Deal 1 4 0
Deal 1 5 4
Deal 2 1 2
Deal 2 2 6
Deal 2 3 1
Deal 2 4 7
Deal 2 5 9
Basically I want to include the fields from fraud_types also and just display 0 in the output if it is not present in the alarms table. How can I achieve this ? Please help
Regards
You can do this with a cross join to get all combinations and then a left outer join:
select d.dealer, f.fraud_id, coalesce(cnt, 0)
from (select distinct dealer from fraud_types) d cross join
fraud_types f left outer join
(select dealer, fraud_id, count(*) as cnt
from fraud_types
group by dealer, fraud_id
) df
on df.dealer = d.dealer and df.fraud_id = f.fraud_id
order by d.dealer, f.fraud_id;
Partitioned outer join is very useful for cases like this:
select a.dealer, f.fraud_id, nvl(a.count,0) count
from fraud_types f
left outer join alarms a
partition by (a.dealer)
on a.fraud_id = f.fraud_id
order by a.dealer, f.fraud_id
This does an outer join between alarms and fraud_types for every value of dealer found in alarms.
--
If the alarms table does not have (fraud,dealer) as key, then you can do a group by before the partition outer join:
select a.dealer, f.fraud_id, nvl(a.count,0) count
from fraud_types f
left outer join (
select fraud_id
, dealer
, sum(count) count
from alarms
group by fraud_id, dealer
) a
partition by (a.dealer)
on a.fraud_id = f.fraud_id
order by a.dealer, f.fraud_id
select distinct f.fraud_id,dealer,
(case when f.fraud_id=t.fraud_id then COUNT else 0 end) counts
from
fraud_types f
left join
alarms t
partition by (dealer)
on f.fraud_id=t.fraud_id
order by dealer

Avoid repeatation of rows for every instance when joined with a table

Hi i have 3 tables and i am trying to join them to get a desire table. I have tried group by and temp tables options to get the desired table but no help. I want to avoid duplicates for every instance of a value in one table from another table.
Table 1 Customer Table:
CstId CstDetails CstType
---------- --------------- ------------
1 address 1 1
2 address 2 1
3 address 3 1
4 address 4 2
5 address 5 2
Table 2 Customer Relationship:
CstId CstGroupId
---------- ----------------
1 4 (this is same as CustomerId)
2 5 (this is same as CustomerId)
3 4 (this is same as CustomerId)
Table 3 Customer Notes:
CstId NotesId NoteTxt
----------- --------- ---------
1 1 note11
1 2 note12
1 3 note13
3 1 note31
4 1 note41
4 2 note42
4 3 note43
4 4 note44
4 5 note45
Now i want the result to be in the below format
Table result:
(NoteId) (Notetxt) (NoteId) (Notetxt)
CstId CstDetails CstGroupId CstNoteId CstNote CstGroupNoteId CstGroupNote
1 address1 4 1 note11 1 note41
1 address1 4 2 note12 2 note42
1 address1 4 3 note13 3 note43
1 address1 4 null null 4 note44
1 address1 4 null null 5 note45
But i am getting CstGroupNote repeated for all the CstNote, which i am trying to avoid.
Is there a way i could achieve this result?
Below is the code i use:
select c.cstid, c.cstdetails, cn.cstnotesid, cn.cstnotetxt
insert into temp1
from customer c
left outer join customernotes cn
on c.cstid = cn.cstid
where c.customertypeid = 1
select cr.cstid, cr.cstgroupid, cn.cstgroupnoteid, cn.cstnotetxt
insert into temp2
from customerrelationship cr
left outer join customernotes cn
on cr.cstgroupid = cn.customerid
select t1.cstid, t1.cstdetails, t1.cstnotesid, t1.cstnotetxt, t2.cstgroupnoteid, t2.cstnotetext
from temp1 t1
left outer join t2
on t1.cstid = t2.cstid
Try:
select CstId,
max(CstDetails) CstDetails,
max(CstGroupId) CstGroupId,
max(CstNoteId) CstNoteId,
max(CstNote) CstNote,
max(CstGroupNoteId) CstGroupNoteId,
max(CstGroupNote) CstGroupNote
from
(select c.CstId,
c.CstDetails,
0 CstGroupId,
n.NotesId CmbNotesId,
n.NotesId CstNoteId,
n.NoteTxt CstNote,
0 CstGroupNoteId,
'' CstGroupNote
from customer c
left outer join customernotes n on c.cstid = n.cstid
where c.customertypeid = 1
union all
select c.CstId,
c.CstDetails,
r.CstGroupId,
n.NotesId CmbNotesId,
0 CstNoteId,
'' CstNote,
n.NotesId CstGroupNoteId,
n.NoteTxt CstGroupNote
from customer c
left outer join customerrelationship r on c.cstid = r.cstid
left outer join customernotes n on r.CstGroupId = n.cstid
where c.customertypeid = 1) u
group by CstId, CmbNotesId
Use a derived table and an outer join
The trick there is the
and cn.cstnotesid = cG.cstnotesid
to link those two on one row
select c.cstid, c.cstdetails, cn.cstnotesid, cn.cstnotetxt
,cG.CstGroupId, cG.cstnotesid, cG.cstnotetxt
from customer c
join customernotes cn
on cn.cstid = c.cstid
outer join (select c.cstid, c.CstGroupId, cn.cstnotesid, cn.cstnotetxt
from customer c
join customernotes cn
on cn.cstid = c.CstGroupId) as cG
on c.cstid = cG.cstid
and cn.cstnotesid = cG.cstnotesid
order by c.cstid, cn.cstnotesid, cG.cstnotesid

SQL 2 left outer joins on same table

I'm doing 2 joins on the same table and I want the following results:
chnl_ptnr_key type1_ky type2_ky
------------- -------- --------
1 1 null
1 2 null
1 null 3
1 null 4
But instead I'm getting
chnl_ptnr_key type1_ky type2_ky
------------- -------- --------
1 1 3
1 2 3
1 2 3
1 2 4
My query is:
SELECT cp.chnl_ptnr_ky, cpmap1.ky as type1_ky, cpmap2.ky as type2_ky
FROM chnl_ptnr cp
LEFT OUTER JOIN chnl_ptnr_oos_map cpmap1 on (cp.chnl_ptnr_ky = cpmap1.chnl_ptnr_ky and cpmap1.typ = 'TYPE1')
LEFT OUTER JOIN chnl_ptnr_oos_map cpmap2 on (cp.chnl_ptnr_ky = cpmap2.chnl_ptnr_ky and cpmap2.typ = 'TYPE2')
WHERE cp.chnl_ptnr_ky = '1111'
Can someone help me to change this query so I get nulls in type1_ky and type2_ky where the row is being returned from the other join?
I need this format because I'm attempting to use it for an iBATIS map.
Many thanks
In your example, the results of the first LEFT JOIN are (1,1) and (1,2). As there are no (1,NULL) records, there will be no (1,NULL,?) records after the next LEFT JOIN.
You probably need a UNION in there somewhere...
SELECT cp.chnl_ptnr_ky, cpmap1.ky as type1_ky, NULL AS type2_ky
FROM chnl_ptnr cp
LEFT OUTER JOIN chnl_ptnr_oos_map cpmap1 on (cp.chnl_ptnr_ky = cpmap1.chnl_ptnr_ky and cpmap1.typ = 'TYPE1')
WHERE cp.chnl_ptnr_ky = '1111'
UNION ALL
SELECT cp.chnl_ptnr_ky, NULL, cpmap2.ky as type2_ky
FROM chnl_ptnr cp
LEFT OUTER JOIN chnl_ptnr_oos_map cpmap2 on (cp.chnl_ptnr_ky = cpmap2.chnl_ptnr_ky and cpmap2.typ = 'TYPE2')
WHERE cp.chnl_ptnr_ky = '1111'