0

下面是我的脚本的一部分。

select a. itemcode, sum(b.quantity) 'y1qty', 
    isnull(null,0) as 'yr2qty', sum(c.amt) 'yr1amt' 
    isnull(null,0) as 'yr2amt',
from ABC a
left join DEF b on a.itemcode = b.itemcode
group by a. itemcode

UNION

select  a1. itemcode, isnull(null,0) as 'yr1qty',
    sum(b1.quantity) 'yr2qty', isnull(null,0) as 'yr1amt',
    sum(c.amt) 'yr2amt' 
from ABC a1
left join DEF b1 on a1.itemcode = b1.itemcode
group by a1.itemcode

表 A:SAmple 输出(基于上面的查询)

itemcode     y1qty  yr2qty   yr1amt      yr2amt
item 001     150      0       200.00       0
item 002      0      300        0         150.00
item 003      0      50         0         100.00
item 004     20      0        150.00       0       

我想插入一个 case 语句,其中逻辑是这样的:如果 y1qty = 0 和 yr2qty = 0 然后等等等等。如果 y1qty = 0 和 y2qty > 0 然后等等等等.. 'DIff'

并旨在实现这一结果:

Table B: 
itemcode     y1qty  yr2qty   Diff      yr1amt      yr2amt
item 001     150      0         0        200.00       0
item 002      0      300       100        0         150.00
item 003      0      50        100        0         100.00
item 004     20      0           0      150.00       0 
item 005     20      30       1000      100.00      200.00
4

2 回答 2

0

您需要将查询包装为子查询并执行以下操作:

select 
  itemcode, 
  y1qty, 
  yr2qty, 
  case when y1qty = 0 and yr2qty = 0 then ... when ... then ... else ... end Diff,
  yr1amt,
  yr2amt
from (
  select a. itemcode, sum(b.quantity) 'y1qty', 
      isnull(null,0) as 'yr2qty', sum(c.amt) 'yr1amt' 
      isnull(null,0) as 'yr2amt',
  from ABC a
  left join DEF b on a.itemcode = b.itemcode
  group by a. itemcode

  UNION

  select  a1. itemcode, isnull(null,0) as 'yr1qty',
      sum(b1.quantity) 'yr2qty', isnull(null,0) as 'yr1amt',
      sum(c.amt) 'yr2amt' 
  from ABC a1
  left join DEF b1 on a1.itemcode = b1.itemcode
  group by a1.itemcode
) t
于 2013-05-15T06:38:16.677 回答
0

专家们,

感谢您所有的及时回复和聪明的头脑,我最终得到了这个解决方案,下面的东西对我有用。只是想分享...

祝大家有个美好的一天!

select t1.itemcode, t1.y1qty, t1.yr2qty,
 CASE 
    WHEN y1qty = 0 AND yr2qty = 0 
        THEN blah blah
    WHEN y1qty = 0 and y2qty >  
        THEN blah blah
    ELSE blah blah
END AS Diff
FROM
(
     SELECT a.itemcode, 
     SUM(b.quantity) AS 'y1qty', 
     ISNULL(NULL,0) AS 'yr2qty', 
     SUM(c.amt) AS 'yr1amt' 
     ISNULL(null,0) AS 'yr2amt',
     FROM ABC a
    LEFT JOIN DEF b ON a.itemcode = b.itemcode
     GROUP BY a.itemcode) t1
UNION 


select t2.itemcode, t2.y1qty, t2.yr2qty,
 CASE 
    WHEN y1qty = 0 AND yr2qty = 0 
        THEN blah blah
    WHEN y1qty = 0 and y2qty >  
        THEN blah blah
    ELSE blah blah
END AS Diff
FROM
(
     SELECT  a.itemcode, 
   ISNULL(NULL,0) AS 'yr1qty',
    SUM(b.quantity) AS 'yr2qty', 
   ISNULL(NULL,0) AS 'yr1amt',
   SUM(c.amt) AS 'yr2amt' 
   FROM ABC a
  LEFT JOIN DEF b ON a.itemcode = b.itemcode
   GROUP BY a.itemcode
    ) t2
于 2013-05-15T10:26:40.703 回答