如何在飞行中添加列?

时间:2015-12-10 11:29:39

标签: sql sql-server sql-server-2008 tsql sql-server-2012

我面临着不同的问题。在select查询中,我想基于其他列值在临时添加临时列。

我有2列

IsOpeningClosingDateToo (tinyint),
HearingDate Date

现在我想检查一下IsOpeningClosingDate = 1然后

Select HearingDate, HearingDate as 'OpeningDate'

如果IsOpeningClosingDate = 2

Select HearingDate, HearingDate as 'ClosingDate'

我试过这样做但失败了:

SELECT 
      ,[HearingDate]
      ,CASE [IsOpeningClosingDate]
       when 1 then [HearingDate] as OpeningDate
       When 0 then [HearingDate] as ClosingDate
       end as 'test'
   ]
  FROM [LitMS_MCP].[dbo].[CaseHearings]

1 个答案:

答案 0 :(得分:3)

我建议返回三列。然后,您可以在应用程序端获取值:

SELECT HearingDate,
       (CASE WHEN IsOpeningClosingDate = 1 THEN HearingDate END) as OpeningDate,
       (CASE WHEN IsOpeningClosingDate = 0 THEN HearingDate END) as ClosingDate
 FROM [LitMS_MCP].[dbo].[CaseHearings];

或者,你可以只提取HearingDateIsOpeningClosingDate并在Python中进行比较。

重要的一点是SQL查询中的列由SELECT修复。您无法在查询中有条件地更改列的名称或类型。