日期:2014-05-18  浏览次数:20507 次

Case的运用
有一个表如下,
ID               InQty         nowQty       InDate
ddj001 50 50 2007-01-24   00:00:00.000
rkz005 40 40 2007-01-25   00:00:00.000
ddj002 80 80 2007-01-26   00:00:00.000
ddj004 70 70 2007-01-27   00:00:00.000

我想要得到结果为

ID               InQty         nowQty       InDate                                             mark
ddj001 50 50 2007-01-24   00:00:00.000           -
rkz005 40 40 2007-01-25   00:00:00.000           -
ddj002 80 80 2007-01-26   00:00:00.000           80
ddj004 70 70 2007-01-27   00:00:00.000           70

mark的取值为:   当inQty> 60   时为   -,否则为nowQty的值.

我能用union   all得到想要的结果,不知道用case行么?



------解决方案--------------------
--try:
select ID,InQty,nowQty,InDate ,mark=case when inQty> 60 then '- ' else nowQty end from tbl
------解决方案--------------------
declare @a table(ID varchar(10), InQty int, nowQty int, InDate datetime)
insert @A SELECT 'ddj001 ', 50 ,50, '2007-01-24 00:00:00.000 '
UNION ALL SELECT 'rkz005 ', 40, 40 , '2007-01-25 00:00:00.000 '
UNION ALL SELECT 'ddj002 ', 80, 80 , '2007-01-26 00:00:00.000 '
UNION ALL SELECT 'ddj004 ', 70, 70 , '2007-01-27 00:00:00.000 '

SELECT ID,INQTY,NOWQTY,INDATE,CASE WHEN NOWQTY> 60 THEN '- ' ELSE LTRIM(NOWQTY) END MARK FROM @A
------解决方案--------------------
語法問題
------解决方案--------------------
请问这个为什么不可以呢?
select ID,InQty,nowQty,InDate ,mark=case (inQty> 60) when 1 then '- ' else nowQty end from tbl
------

select ID,InQty,nowQty,InDate,mark=(case when inQty> 60 then '- ' else nowQty end) from tbl