Duplicate record after joining two tables - sql-server

I am currently having trouble with my query after joining two tables I am getting duplicated records. What i want to do is get the details from table 1 and the payment record from table 2 with same date.. here is my query.
SELECT dbo.tblautoipekonek.ipno,
dbo.tblautoipekonek.awbno,
dbo.tblautoipekonek.ipamount,
dbo.tblautoipekonek.orno,
dbo.tbladdfunds.username,
dbo.tbladdfunds.newctfbal,
dbo.tbladdfunds.addedctfamt,
dbo.tbladdfunds.oldctfbal,
dbo.tbladdfunds.newipbal,
dbo.tbladdfunds.addedipamt,
dbo.tbladdfunds.oldipbal,
dbo.tbladdfunds.date,
dbo.tblautoipekonek.date AS Expr1
FROM dbo.tblautoipekonek
LEFT OUTER JOIN dbo.tbladdfunds
ON dbo.tblautoipekonek.date = dbo.tbladdfunds.date
WHERE
( dbo.tblautoipekonek.date = '06/06/2014' )

Hi you can use "Distinct" keyword at after "select" keyword. it will get the single record.
Good to replace dbo.tablename with alias name give to tablename as
select
distinct
auto.IPNo, ... ---here you can add other column of this table.
fund.AddedCTFAmt --same thing done here.
FROM tblAutoIPEkonek auto
LEFT OUTER JOIN dbo.tblAddfunds fund
ON auto.Date = fund.Date --try to add more join condition so filteration done here of data which is fastest/
WHERE (auto.Date = '06/06/2014')

SELECT DISTINCT dbo.tblautoipekonek.ipno,
dbo.tblautoipekonek.awbno,
dbo.tblautoipekonek.ipamount,
dbo.tblautoipekonek.orno,
dbo.tbladdfunds.username,
dbo.tbladdfunds.newctfbal,
dbo.tbladdfunds.addedctfamt,
dbo.tbladdfunds.oldctfbal,
dbo.tbladdfunds.newipbal,
dbo.tbladdfunds.addedipamt,
dbo.tbladdfunds.oldipbal,
dbo.tbladdfunds.date,
dbo.tblautoipekonek.date AS Expr1
FROM dbo.tblautoipekonek
LEFT OUTER JOIN dbo.tbladdfunds
ON dbo.tblautoipekonek.date = dbo.tbladdfunds.date
WHERE
( dbo.tblautoipekonek.date = '06/06/2014' )
GROUP BY dbo.tblautoipekonek.ipno,
dbo.tblautoipekonek.awbno,
dbo.tblautoipekonek.ipamount,
dbo.tblautoipekonek.orno,
dbo.tbladdfunds.username,
dbo.tbladdfunds.newctfbal,
dbo.tbladdfunds.addedctfamt,
dbo.tbladdfunds.oldctfbal,
dbo.tbladdfunds.newipbal,
dbo.tbladdfunds.addedipamt,
dbo.tbladdfunds.oldipbal,
dbo.tbladdfunds.date,
dbo.tblautoipekonek.date AS Expr1

Not sure if this will work for you but this is what I would use:
SELECT
p.ipno,
p.awbno,
p.ipamount,
p.orno,
f.username,
f.newctfbal,
f.addedctfamt,
f.oldctfbal,
f.newipbal,
f.addedipamt,
f.oldipbal,
f.date,
p.date Expr1
FROM
dbo.tblautoipekonek p
CROSS APPLY
(
SELECT TOP 1
*
FROM
dbo.tbladdfunds f
WHERE
p.date = f.date
ORDER BY
f.newipbal DESC
) f
This will get you one line from each entry in dbo.tblautoipekonek joined with the matching date entry from dbo.tbladdfunds which has the highest value in newipbal

Related

CROSS APPLY Returning more than expected number of rows

I would like to only return one row from the CROSS APPLY, however I am returning multiple OwnershipID rows, different from what I get in the eSub subquery. Can someone please point out what I'm doing wrong?
SELECT
o2.OwnershipID,
eSub.AssetID,
esub.EntityID,
esub.Entity
FROM tblOwnership o2
CROSS APPLY
(
SELECT TOP 1
a1.AssetID,
e1.EntityID,
e1.Entity,
o1.OwnershipID
FROM tblAssets a1
INNER JOIN tblOwnership o1 ON a1.AssetID = o1.AssetID
INNER JOIN tblEntity e1 ON o1.EntityID = e1.EntityID
WHERE 1=1
AND o1.OwnershipID = o2.OwnershipID
AND a1.AssetID = 1996323640
ORDER BY o1.OwnershipID DESC, o1.[Date] DESC
) eSub
WHERE 1=1
AND o2.AssetID = 1996323640
ORDER BY o2.OwnershipID DESC
I would like to return the top 1 ownershipID for each assetID in the table.
If you want to look at all records for a given AssetID, then you should only apply a range on that column in the where clause of your cross apply. Each combination of [AssetID, EntityID, OwnershipID] appears to be unique in your data. If you add ranges on all three fields, then there will be only one matching record (itself).
Working with your fiddle I came up with this.
SELECT o2.AssetID,
o2.EntityID,
o2.OwnershipID as 'o2OwnID',
eSub.OwnershipID as 'eOwnID'
FROM tblOwnership o2
CROSS APPLY
(
SELECT TOP 1 o1.OwnershipID
FROM tblOwnership o1
WHERE o1.AssetID = o2.AssetID
/*AND o1.EntityID = o2.EntityID
AND o1.OwnershipID = o2.OwnershipID*/
ORDER BY o1.OwnershipID DESC
) eSub
ORDER BY o2.OwnershipID DESC

sql server - How to Get all distinct value in group by column from two table and count from another table for each value

I have 3 tables in that 2 tables are master table and 3rd is transaction table. i need to get count from transaction table for each value in other two table without loosing rows in mater table
i need result like below
Table layout for understanding
This is the code i have tried,
select s.status_name, e.machine_group_name, qty = COALESCE(COUNT(e.id),0)
from tbl_status s
left outer JOIN tbl_transaction as e ON e.status_name = s.status_name
group by e.machine_group_name, s.status_name
This is solution i have figured:
select m.machine_group_name, s.status_name, qty = COUNT(e.id) from
tbl_machine_group as m
cross join tbl_status as s
left outer join tbl_transaction as e on e.status_name = s.status_name
and e.machine_group_name = m.machine_group_name
group by m.machine_group_name, s.status_name
order by machine_group_name
select
MC_Group_Name
,Status_Name
,count(1) as [Count of Transaction]
from
tbl_Transaction tbl_3
left join tbl_Machine_Group tbl_1
on tbl_3.MC_Group_Name = tbl_1.MC_Group_Name
left join tbl_Status tbl_2
on tbl_3.Status_Name = tbl_2.Status_Name
group by
MC_Group_Name
,Status_Name

SQL Server LEFT OUTER JOIN HAVING criteria restricts results [duplicate]

I have this query in MySQL:
SELECT pr.*, pr7.value AS `room_price_high`
FROM `jos_hp_properties` pr
LEFT OUTER JOIN `jos_hp_properties2` pr7 ON pr7.property=pr.id
WHERE pr7.field=23
The jos_hp_properties table has 27 rows but the query only returns one. Based on this question I think it may be because of the WHERE clause. The jos_hp_properties2 table has fields id, property, field, value, where field is a foreign key to a third table (which I don't need to get data from).
Is there a way to select all the rows from the first table, including the value from table #2 where the field is 23 (or NULL if there is no field 23)?
Sure. Move the WHERE condition to the JOIN:
SELECT pr.*, pr7.value AS `room_price_high`
FROM `jos_hp_properties` pr
LEFT JOIN `jos_hp_properties2` pr7
ON pr7.property=pr.id
AND
pr7.field=23
You must place the pr7 criteria in the join, not in the where clause. The where clause works on the entire result set AFTER the join has been performed.
SELECT pr.*, pr7.value AS `room_price_high`
FROM `jos_hp_properties` pr
LEFT OUTER JOIN `jos_hp_properties2` pr7 ON pr7.property=pr.id and pr7.field=23
Try this:
SELECT pr.*, pr7.value AS `room_price_high`
FROM `jos_hp_properties` pr
LEFT OUTER JOIN `jos_hp_properties2` pr7 ON pr7.property=pr.id
WHERE (pr7.field=23 OR pr7.field is null)
You can also use a CTE (Common Table Expression) to do the select, then use the CTE to do the left join..
wrc (parentid, childid) as (
select parentid, childid
from placechild
where relationshipid in (select id from placerelationship where relationship = 'Winter Region Capital')
),
stw (cnid, coid, capid, st_or_te, sid, scid,wcid) as (
select s.cnid, s.coid, s.capid, s.st_or_te, s.sid, s.scid, w.childid
from stcap s
left join wrc w
on s.sid = w.parentid
)
select * from stw

TOP And DISTINCT in one query

How can i use top and distinct in one statement i am using this but not success . I dont know what i am doing wrong .
Below is my statement that i am using but giving me exception.
SELECT TOP 30 * from
(
SELECT DISTINCT
Bill.CLIENTID,Bill.TRANDATE,Bill.TRANTYPE,Bill.DUE,Bill.AMOUNT,Bill.paid,ORDE_.INVDATE ,Bill.TRANDESC,Bill.INVNUM
FROM BILLING Bill LEFT OUTER JOIN ORDE_ ON Orde_.INVNUM = Bill.INVNUM
WHERE Bill.CLIENTID = 1047 )
Missing table alias for the subquery may be the cause of your error. You don't need a subquery, you can use both Distinct and Top together.
Top(n) records depend on the order of the result set. So don't forget to explicitly Order your results.
SELECT DISTINCT TOP(30) Bill.CLIENTID,Bill.TRANDATE,Bill.TRANTYPE,Bill.DUE,Bill.AMOUNT,
Bill.paid,ORDE_.INVDATE ,Bill.TRANDESC,Bill.INVNUM
FROM BILLING Bill LEFT OUTER JOIN ORDE_ ON Orde_.INVNUM = Bill.INVNUM
WHERE Bill.CLIENTID = 1047
ORDER BY ....
It may help
SELECT TOP 30 * from
(
SELECT DISTINCT
Bill.CLIENTID,Bill.TRANDATE,Bill.TRANTYPE,Bill.DUE,Bill.AMOUNT,Bill.paid,ORDE_.INVDATE ,Bill.TRANDESC,Bill.INVNUM
FROM BILLING Bill LEFT OUTER JOIN ORDE_ ON Orde_.INVNUM = Bill.INVNUM
WHERE Bill.CLIENTID = 1047 ) Alias

mssql query join to work out esclation person based on discounts percentage

Hi I have the below working query(mssql)
select
max(load_number) load_number,max(linediscount) maxlinediscount,max(CustomerBand) customer_band
from [Linked_Order_lines]
join [Customer_Order_Summary]
on [Customer_Order_Summary].[CustomerOrderID]=[Linked_Order_lines].[load_number]
join [Customers]
on Customers.CustomerName=Customer_Order_Summary.CustomerName
join Customer_Order_lines
on Customer_Order_Summary.CustomerOrderID=Customer_Order_lines.CustomerOrderID
join price_escalation_bands
on price_escalation_bands.band=Customer_Order_Summary.CustomerBand
where [linked_order_id] in
(
select [linkedorderid] from
[Linked_Order_Summary] join [Linked_Order_lines] on
[Linked_Order_Summary].[linkedorderid] = [Linked_Order_lines].[linked_order_id]
where [load_number]='7'
)
and Customer_Order_lines.linestatus='current'
group by load_number
This produces the result
In this query, I have already joined to the table price_escalation_bands which looks like this:
What I am wanting to do, is compare the maxlinediscount from my query with the discount column of table price_escalation_bands and return the user id (fk_salesman_userid) of the record in the table that is the next greatest. so discount of 11 would go to discount 15 and return fk_salesman_userid 9. if the discount was 18, it would go to 100 and return fk_salesman_userid 21.
I am basically trying to work out the fk_salesman_userid that can approve the discount in maxlinediscount
So desired output would be:
Do I need a case statement and if so how do I use it with the max statements in my existing select statement?
thanks in advance as aways
While joining the price_escalation_bands you can use one more condition for discount.
Check the FIDDLE. Here I have tried with the result in a temp table. You can try the same subquery with your join price_escalation_bands by passing the max(linediscount).
Hope this will help you.
Final Working syntax:
IF OBJECT_ID('tempdb..#linkloads') IS NOT NULL
BEGIN
DROP TABLE #linkloads
END
CREATE TABLE #linkloads
(
maxlinediscount [decimal](10,3),
customer_band [varchar](50),
load_number [int],
totalcost [decimal](10,3),
period [datetime],
CreditLimit[decimal](10,3),
CurrentBalance[decimal](10,3),
CustomerName [varchar](100),
TotalCubes[decimal](10,3),
TreatedCubes[decimal](10,3),
NormalCubes[decimal](10,3),
PricingIssue[bit]
);
insert into #linkloads
select max(linediscount) maxlinediscount,max(CustomerBand) customer_band,max(load_number) load_number,max(totalcost) totalcost,max(Customer_Order_Summary.PeriodStart) period,max(Customers.CreditLimit) CreditLimit ,max(Customers.CurrentBalance)CurrentBalance,max(Customer_Order_Summary.CustomerName)CustomerName,max(TotalCubes) TotalCubes,max(TreatedCubes)TreatedCubes ,max(TotalCubes-TreatedCubes) as NormalCubes,sum(case when pricingissue=1 THEN 1 ELSE 0 END) pricingissue
from [Linked_Order_lines]
join [Customer_Order_Summary]
on [Customer_Order_Summary].[CustomerOrderID]=[Linked_Order_lines].[load_number]
join [Customers]
on Customers.CustomerName=Customer_Order_Summary.CustomerName
join Customer_Order_lines
on Customer_Order_Summary.CustomerOrderID=Customer_Order_lines.CustomerOrderID
where [linked_order_id] in
(
select [linkedorderid] from
[Linked_Order_Summary] join [Linked_Order_lines] on
[Linked_Order_Summary].[linkedorderid] = [Linked_Order_lines].[linked_order_id]
where [load_number]='10'
)
and Customer_Order_lines.linestatus='current'
group by load_number;
select * from #linkloads;
select load_number,maxlinediscount,customer_band,[Salesman_Discounts_per_band].fk_salesman_userid,totalcost,period,creditlimit,currentbalance,customername,totalcubes,treatedcubes,normalcubes,pricingissue from #linkloads
left outer JOIN [Salesman_Discounts_per_band] on [Salesman_Discounts_per_band].band=#linkloads.customer_band
AND [Salesman_Discounts_per_band].[discount_allowed] = (
SELECT top 1 [Salesman_Discounts_per_band].[discount_allowed]
FROM [Salesman_Discounts_per_band]
WHERE [Salesman_Discounts_per_band].band=#linkloads.customer_band
AND [Salesman_Discounts_per_band].[discount_allowed]<=#linkloads.maxlinediscount
ORDER BY [Salesman_Discounts_per_band].[discount_allowed]
)
;

Resources