0

您好,我有 2 个表,它们有 2 个这样的列。

DocumentNumber       Price

我在表格中显示了相同的 DocumentNumbers,每个文档编号的计数和价格差异。这是我的查询

select DocumentNumber, max(cnt_s) as documentNumber1, max(cnt_s2) as documentNumber1,
       max(price_s) - max(price_s2) as PriceDifference
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;

我只想在价格差异之前添加 sheet1 的价格和 sheet2 的价格。建议我一些查询。

4

2 回答 2

1

尝试

SELECT DocumentNumber, 
       MAX(cnt_s) cnt_s, 
       MAX(cnt_s2) cnt_s2,
       MAX(price_s) price_s,
       MAX(price_s2) price_s2,
       MAX(price_s) - MAX(price_s2) PriceDifference
 FROM 
(
  SELECT DocumentNumber, 
         COUNT(*)   cnt_s, 
         0          cnt_s2, 
         SUM(price) price_s, 
         0          price_s2
    FROM Sheet
   GROUP BY DocumentNumber
  UNION ALL    
  SELECT DocumentNumber, 
         0          cnt_s, 
         COUNT(*)   cnt_s2,
         0          price_s, 
         SUM(price) price_s2
    FROM Sheet2
   GROUP BY DocumentNumber
) q
 GROUP BY DocumentNumber

这是SQLFiddle演示。

请注意,在您的原始查询中,您返回max(cnt_s)并使用您不应该执行max(cnt_s2)的相同别名documentNumber1

更新正如你所问的,这里有一个版本JOIN

SELECT s.DocumentNumber, 
       s.cnt_s, 
       s2.cnt_s2, 
       s.price_s,
       s2.price_s2,
       s.price_s - s2.price_s2 PriceDifference
 FROM 
(
  SELECT DocumentNumber, 
         COUNT(*)   cnt_s, 
         SUM(price) price_s
    FROM Sheet
   GROUP BY DocumentNumber
) s JOIN     
(
  SELECT DocumentNumber, 
         COUNT(*)   cnt_s2,
         SUM(price) price_s2
    FROM Sheet2
   GROUP BY DocumentNumber
) s2 ON s.DocumentNumber = s2.DocumentNumber

这是SQLFiddle演示(带有两个查询)。

请注意,此查询假定您始终DocumentNumber同时拥有SheetSheet2。不匹配将被过滤掉JOIN。因此,您可能需要使用外连接。

于 2013-06-22T05:39:24.363 回答
0

干草可以包括拼写错误。如果发生错误,请告诉我

 SELECT temp.DN, MAX(temp.CNT1) as documentNumber1, MAX(temp.CNT2) as documentNumber1,
 MAX(temp.P1) - MAX(temp.P2) as PriceDifference, temp.P1 as Price1 , 
 temp.P2 as Price2 FROM 
 ((SELECT tbl.DocumentNumber 
 as DNumber,tbl.cnt_s as CNT1,tbl.cnt_s2 as CNT2,
 tbl.price_s as P1,tbl.price_s2 as P2 FROM 
    (select DocNum, count(*) as cnt_s, 0 as cnt_s2,
    SUM(price) as price_s, 0 as price_s2
    FROM Sheet s) 
    UNION ALL
    (SELECT DocNum, 0, count(*) as cnt_s2,
     0, sum(price) as price_s2
     FROM Sheet2 s2
     )
  ) as tbl GROUP BY tbl.DoucmentNumber
 ) temp
group by temp.DN;
于 2013-06-22T05:54:04.583 回答