I have these tables, rolls and rollsout. I would like to perform a join and do some math .
rolls
|size|
------
|3x3|
|4x4|
|3x3|
|3x3|
rollsout
|type|
------
|3x3|
Expected output after SUBTRACTing, JOINing ==>
|size|Remaining(table1 - table2)|
--------------------------------
|3x3| 2 |
|4x4| 1 |
My code:
SELECT tarpaulin.size, COUNT( * ) , tarpaulinout.Ww, tarpaulinout.dc
FROM tarpaulin LEFT JOIN (SELECT size AS Ww, COUNT( * ) AS dc FROM tarpaulinout
GROUP BY size) AS tarpaulinout ON tarpaulin.size = tarpaulinout.Ww
GROUP BY tarpaulin.size
But the O/P for the above code is
|size|count(*)|size |dc |
----------------------------
|3x3|3 | 3x3 |1 |
|4x4|1 | NILL| NILL |
i can get this close, kindly instruct me on how to achieve my desired output. Thanks in advance.
You can just UNION the two sets together, then take a SUM across both, ie
select size, sum(counter) remaining
from
(
select size, 1 counter
from rolls
union all
select type, -1 counter
from rollsout
) x
group by size;
You need to group the first table and second table separately on size
to get the count of records and then perform a LEFT JOIN on the size
attribute to get all the records from tarpaulin
table and the matching ones from tarpaulinout
table, and do the subtraction, as below.
SELECT a.size, a.rcount - ISNULL(b.rcount, 0)
FROM
(SELECT size, count(*) FROM tarpaulin GROUP BY size) as a
LEFT JOIN (SELECT size, count(*) FROM tarpaulinout GROUP BY size) as b
ON a.size = b.size
Select x.Size,(x.Cnt1 - Isnull(y.Cnt2, 0)) AS Remaining
From
(Select r.Size,count(r.Size) Cnt1
From rolls r
Group by r.Size)x
Left Outer join
(Select ro.Type,Count(ro.Type) Cnt2
From rollsout ro
Group by ro.Type)y
On x.Size = y.Type
SELECT a.size, a.Rcount - b.Acount FROM (SELECT size, COUNT( * ) AS Rcount FROM tarpaulin GROUP BY size ) AS a LEFT JOIN ( SELECT size, COUNT( * ) AS Acount FROM tarpaulinout GROUP BY size ) AS b ON a.size = b.size
对Vikdor代码的一点修改对我有用,感谢快速输入的人:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.