mysql如何加入表并做一些数学运算

时间:2012-10-30 03:14:49

标签: mysql sql

我有这些表,滚动和推出。我想进行一次加入并做一些数学运算。

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

rollsout

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

SUBTRACTING,JOINing ==>

之后的预期输出
      |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 个答案:

答案 0 :(得分:2)

你可以将这两个集合UNION,然后在两个集合中使用SUM,即

select size, sum(counter) remaining
from
(
    select size, 1 counter
    from rolls
    union all
    select type, -1 counter
    from rollsout
) x
group by size;

答案 1 :(得分:0)

您需要在size上分别对第一个表和第二个表进行分组以获取记录数,然后对size属性执行LEFT JOIN以获取{{1}的所有记录}表和来自tarpaulin表的匹配表,并进行减法,如下所示。

tarpaulinout

答案 2 :(得分: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

答案 3 :(得分: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代码的一点修改对我有用,感谢快速输入的人:)