I have a table with the following set of information:
r-Id v-id cost
---------------------------
i-1234 v-1234 0.5
v-1234 - 1.25
I can't quite put my finger on a query for a scenario like this: If a r-Id consists of a v-id, sum up the corresponding v-id cost to the r-id.
So i-1234 cost should be cost: 1.75. Any help is appreciated. Thanks.
Does this do what you want?
select t.r_id, max(t.cost) + coalesce(sum(t2.cost), 0)
from table t left join
table t2
on t.v_id = t2.r_id
group by t.r_id;
This produces the output you want for the data provided. If the r_id ("i-1234") could be repeated multiple times, then this is not quite the right query.
EDIT:
If the r_id could appear multiple times, then you need to pre-aggregate by it:
select t.r_id, sumcost + coalesce(sum(t2.cost), 0)
from (select t.r_id, sum(t.cost) as sumcost
from table t
group by t.r_id
) t left join
table t2
on t.v_id = t2.r_id
group by t.r_id, sumcost,
Related
I have two tables that has the same columns numbers and names
and I want to join its columns.
I have this table called inicial_dolares
And have this other table called inicial_cordobas
I am looking for this result
I've tried do this with joins but does not work.
the common column is id_arqueo is a integer.
and I tried this SQL union but vertically
but does not work.
SELECT IC.id_arqueo,
IC.id_detalle,
IC.descripcion,
IC.denominacion,
IC.cantidad,
IC.total,
ID.id_arqueo,
ID.id_detalle,
ID.descripcion,
ID.denominacion,
ID.cantidad,
ID.total
FROM dbo.inicial_cordobas IC
LEFT JOIN dbo.inicial_dolares ID
ON ID.id_arqueo = IC.id_arqueo
--this query returns to me 168 rows because the join looks for coincidence and
--one table has 14 and the other has 12 rows.
you need row_number() to join your 2nd table.
SELECT IC.id_arqueo,
IC.id_detalle,
IC.descripcion,
IC.denominacion,
IC.cantidad,
IC.total,
ID.id_arqueo,
ID.id_detalle,
ID.descripcion,
ID.denominacion,
ID.cantidad,
ID.total
FROM
(select row_number() over (order by id_detalle) rn, * from dbo.inicial_cordobas) IC
LEFT JOIN
(select row_number() over (order by id_detalle) rn , * from dbo.inicial_dolares) ID
ON ID.id_arqueo = IC.id_arqueo and IC.rn = ID.rn
The id_detalle columns also have a relationship that can be expressed mathematically and used:
SELECT IC.id_arqueo,
IC.id_detalle,
IC.descripcion,
IC.denominacion,
IC.cantidad,
IC.total,
ID.id_arqueo,
ID.id_detalle,
ID.descripcion,
ID.denominacion,
ID.cantidad,
ID.total
FROM dbo.inicial_cordobas IC
LEFT JOIN dbo.inicial_dolares ID
ON ID.id_arqueo = IC.id_arqueo
AND ic.id_detalle + 14 = id.id_detalle
The id_detalle in ic is always 14 less than the id_detalle in id so we can make a joint condition where we add 14 to the value in ic and then relate it to the value in id
This is possibly an important learning point that joins don't have to always take the form tableA.columnA = tableB.columnB. Anything that can be expressed as a truth may work as a join condition, including formulas and maths operations on either side of the =
I have 3 tables
tb_spp
tb_daycare
tb_antarjemput
Here is the contents of all three tables:
tb_spp
tb_daycare
tb_antarjemput
I want outpunya like this
And for the last output is limit 1 like this:
How to master?
You can refer my query for option 1.
select T1.kode,
T1.Nominal_spp,
T2.Nominal_antarjemput,
(IFNULL(T1.Nominal_spp, 0)*2 + IFNULL(T2.Nominal_antarjemput, 0)) as Total
from tb_spp as T1
left join tb_antarjemput as T2 on T1.kode = T2.kode
I am trying to create an update query that will update my table values based on pallet number match.
SELECT [pallet] [quantity]
FROM dba.Inventory
This will returns 2 columns, one with pallet and the other with count.
I need to put this in a update statement that will match each pallet between here and table TABLE1 and update the counts in TABLE1
Use Common Table Expression.
Syntax goes like
with CTE_Values()
AS
( --- Your Statement---)
Update T
Set Col = C.col
From Table T Join CTE_Values C
On .....
I think that one easy solution (without evaluating the SELECT itself that looks quite convoluted) is to put the whole SELECT into a CTE and use it as source for your update. Something like this:
;WITH SrcCte AS (
SELECT pallet, SUM(total) as quantity
FROM (
SELECT r1.pallet, total
FROM
(SELECT plet_nbr, COUNT(serl_nbr) as total FROM Inventory group by plet_nbr )c1
right join
(select pallet from dbo.RFS where status NOT LIKE 'Not Available')r1
on r1.pallet = c1.plet_nbr
UNION all
Select r2.pallet, sum(iloc_qty) as total
FROM
(SELECT plet_nbr, iloc_qty FROM Inventory WHERE([matl_nbr] Like '#%')) c2
right join
(select pallet from dbo.RFS where status NOT LIKE 'Not Available') r2
on r2.pallet = c2.plet_nbr
where iloc_qty is not null
GROUP BY r2.pallet
)
AS final
GROUP BY pallet
)
UPDATE Dest
SET Dest.Cnt = Src.Quantity
FROM Table1 AS Dest
JOIN SrcCte AS Src ON Src.pallet = Dest.pallet
I have three tables:
Plans(PlanID(key), Capacity)
CustomerInProject(VahedID, cinpid(key))
Vahed(VahedID(key), PlanID,...)
This query shows number of houses with the same PlanID (map) that people hired:
select
count(*)
from
Vahed as v2,
CustomerInProject
where
CustomerInProject.VahedID = v2.VahedID
group by PlanID
Plans has an int field named Capacity. I want to subtract Capacity from the above query. How can I do that?
Something like this should do it:
select p.PlanID, count(*) - p.Capacity
from Vahed as v2
join CustomerInProject c
on c.VahedID = v2.VahedID
join Plan p
on p.PlanID = c.PlanID /* or v.PlanID, it's not clear from the question */
group by p.PlanID, p.Capacity
On the 6th line, you may want to replace c.PlanID with v.PlanID - I don't know the exact table schema.
select sum(cnt)
from
(select capacity*-1 as cnt from
plans
union
select count(*) as cnt from Vahed as v2
inner join
CustomerInProject on
CustomerInProject.VahedID = v2.VahedID
group by PlanID )
I have following sql query and my left join is not giving me distinct result please help me to trace out.
SELECT DISTINCT
Position.Date,
Position.SecurityId,
Position.PurchaseLotId,
Position.InPosition,
ISNULL(ClosingPrice.Bid, Position.Mark) AS Mark
FROM
Fireball_Reporting.dbo.Reporting_DailyNAV_Pricing POSITION WITH (NOLOCK, READUNCOMMITTED)
LEFT JOIN Fireball.dbo.AdditionalSecurityPrice ClosingPrice WITH (NOLOCK, READUNCOMMITTED) ON
ClosingPrice.SecurityID = Position.PricingSecurityID AND
ClosingPrice.Date = Position.Date AND
ClosingPrice.SecurityPriceSourceID = #SourceID AND
ClosingPrice.PortfolioID IN (5,6)
WHERE
DatePurchased > #NewPositionDate AND
Position.Date = #CurrentPositionDate AND
InPosition = 1 AND
Position.PortfolioId IN (
SELECT
PARAM
FROM
Fireball_Reporting.dbo.ParseMultiValuedParameter(#PortfolioId, ',')
) AND
(
Position > 1 OR
Position < - 1
)
Now here in above my when I use LEFT JOIN ISNULL(ClosingPrice.Bid, Position.Mark) AS Mark and LEFT JOIN it is giving me more no of records with mutiple portfolio ids
for e.g . (5,6)
If i put portfolioID =5 giving result as 120 records
If i put portfolioID =6 giving result as 20 records
When I put portfolioID = (5,6) it should give me 140 records
but it is giving result as 350 records which is wrong . :(
It is happening because when I use LEFT JOIN there is no condition of PurchaseLotID in that as table Fireball.dbo.AdditionalSecurityPrice ClosingPrice not having column PurchaseLotID so it is giving me other records also whoes having same purchaseLotID's with diferent prices .
But I dont want that records
How can I eliminate those records ?
You get one Entry per DailyLoanAndCashPosition.PurchaseLotId = NAVImpact.PurchaseLotId
which would mean you must have more entrys in with the same PurchaseLotId
The most likely cause is that the left join produces duplicated PurchaseLotIds. The best way to know if if you perform a select distinct(PurchaseLotId) on your left side of the inner join.