0

我有这些桌子,卷和推出。我想执行一个连接并做一些数学运算。

劳斯莱斯

      |size|
      ------
      |3x3| 
      |4x4| 
      |3x3| 
      |3x3| 

推出

      |type|
      ------
      |3x3| 

减去,加入后的预期输出==>

      |size|Remaining(table1 - table2)|
      --------------------------------
      |3x3|   2                       |                 
      |4x4|   1                       |               

我的代码:

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

但上述代码的 O/P 是

      |size|count(*)|size |dc    |
      ----------------------------
      |3x3|3        | 3x3 |1     |
      |4x4|1        | NILL| NILL |

我可以做到这一点,请指导我如何实现我想要的输出。提前致谢。

4

4 回答 4

2

您可以将这两组联合起来,然后对两者进行求和,即

select size, sum(counter) remaining
from
(
    select size, 1 counter
    from rolls
    union all
    select type, -1 counter
    from rollsout
) x
group by size;
于 2012-10-30T03:38:47.397 回答
0
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 代码的一些修改对我有用,感谢快速输入的家伙:)

于 2012-10-30T03:49:26.297 回答
0

您需要将第一个表和第二个表分别分组size以获取记录数,然后对size属性执行 LEFT JOIN 以获取表中的所有记录和tarpaulin表中匹配的记录,然后进行tarpaulinout减法,如下所示。

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
于 2012-10-30T03:28:00.593 回答
0
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
于 2012-10-30T03:31:53.367 回答