如何在联合中使用case语句

时间:2013-05-15 06:28:44

标签: mysql

以下是我脚本的一部分。

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然后blah blah ..'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

2 个答案:

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

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