使用SQL在查询中添加两列

时间:2013-06-22 04:50:39

标签: sql group-by having

您好我有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的价格。 建议我一些疑问。

2 个答案:

答案 0 :(得分: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 演示(包含两个查询)。

请注意,此查询假定DocumentNumberSheet中始终有Sheet2。错误将由JOIN过滤掉。因此,您可能需要使用外部联接。

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