日期:2014-05-17  浏览次数:20353 次

询问一个SQL如何实现判断查询的问题
   这是我现在的语句 
strSql2.Append("SELECT a.SystemContractID, a.Income, a.TotalMargin, a.UserCode,a.StrategyID, b.StrategyName FROM OrderProfit_History as a INNER JOIN Strategy as b ON a.StrategyID = b.StrategyID");
   OrderProfit_History表中和Strategy 表中都有StrategyID,但是只有Strategy 表中的
StrategyID 有对应的StrategyName,并且OrderProfit_History表中有Strategy 表所没有的StrategyID。现在的语句执行结果是,返回OrderProfit_History表中所有的StrategyID 在Strategy 表中存在的数据,并显示对应的StrategyName。
    我下面想实现的是,显示OrderProfit_History表中所有的数据,如果StrategyID 在Strategy 表中存在,就显示StrategyName ,反之,则没有对应的StrategyName ,那就在StrategyName 项中用StrategyID 替代吧。 
     表达的应该清楚了吧,本人对SQL不是很懂,不知道我说的这个逻辑能不能用一条SQL语句实现?
SQL select

------解决方案--------------------
SELECT a.SystemContractID, 
       a.Income, 
       a.TotalMargin, 
       a.UserCode,
       a.StrategyID, 
       ISNULL(b.StrategyName,a.StrategyID) StrategyName 
FROM OrderProfit_History as a 
INNER JOIN Strategy as b 
ON a.StrategyID = b.StrategyID

------解决方案--------------------
if object_id('OrderProfit_History', 'u') is not null
drop Table OrderProfit_History
Create Table OrderProfit_History
(
  ID int identity(1, 1) primary key not null,
  StrategyID int not null,
  OrderID int not null 
)
Insert into OrderProfit_History  
Select 1, 2
Union all Select 2,2 Union all Select 3,3
Union all Select 4,4
Union all Select 5,5
Union all Select 6,6
Union all Select 7,7
Union all Select 8,8
if OBJECT_ID('Strategy', 'u') is not null
drop table Strategy
Create Table Strategy
(
 ID int identity(1, 1) primary key not null,
 StrategyID int not null,
  StrategyName varchar(128) not null 
)
Insert into Strategy
Select 1, 'aaaa'
Union all Select 2,'bbbb'
Union all Select 3,'cccc'
Union all Select 4,'dddd'

Select a.StrategyID, 
  ISNULL(b.StrategyName, CONVERT(Varchar(32), a.StrategyID)) as StrategyName
From OrderProfit_History a Left Outer Join Strategy b On a.StrategyID = b.StrategyID