0

我有 2 张桌子。每个表有两列。

DocumentNumber      price

我想使用查询来显示每个表中相同的文档编号和文档编号的计数。我使用了这段代码。

Select  Sheet.DocumentNumber , Sheet2.DocumentNumber ,Count(sheet.documentnumber) , Count(sheet2.documentnumber) 

        From Sheet,Sheet2
        where sheet.DocumentNumber=sheet2.DocumentNumber

        group by sheet.DocumentNumber , Sheet2.DocumentNumber

但它不是计算文档编号,而是向我显示两列的笛卡尔坐标。

我想显示每张桌子的价格和(sheet.price)减去(sheet2.price)

请完成我的查询。

4

1 回答 1

1

您应该使用正确的连接语法。特别是,为此,您应该使用full outer join,因为文档可能在一个或另一个表中没有记录。

其次,因为你不想计算重复,你需要计算一些东西。以下假设id每个表中都有一列(某种):

Select  coalesce(s.DocumentNumber, s2.DocumentNumber) as DocumentNumber,
        Count(distinct s.id), Count(distinct s2.id)
From Sheet s full outer join
     Sheet2 s2
     on s.DocumentNumber = s2.DocumentNumber
 group by  coalesce(s.DocumentNumber, s2.DocumentNumber);

如果您没有id列,或者您的数据库不支持full outer join,则以下内容也可以使用:

select DocumentNumber, max(cnt_s) as cnt_s, max(cnt_s2) as cnt_s2
from ((select DocumentNumber, count(*) as cnt_s, 0 as cnt_s2
       from Sheet s
       group by DocumentNumber
      ) union all
      (select DocumentNumber, 0, count(*) as cnt_s2
       from Sheet2 s2
       group by DocumentNumber
      )
     ) t
group by DocumentNumber;

编辑:

这种union all方法实际上更适合价格:

select DocumentNumber, max(cnt_s) as cnt_s, max(cnt_s2) as cnt_s2,
       max(price_s) - max(price_s2)
from ((select DocumentNumber, count(*) as cnt_s, 0 as cnt_s2,
              sum(price) as price_s, 0 as price_s2
       from Sheet s
       group by DocumentNumber
      ) union all
      (select DocumentNumber, 0, count(*) as cnt_s2,
              0, sum(price) as price_s2
       from Sheet2 s2
       group by DocumentNumber
      )
     ) t
group by DocumentNumber;

注意:此版本将缺失的价格视为 0。对于这种情况,您可能需要替换0NULL

于 2013-06-21T19:07:50.097 回答