想要sql查询,它给出了包含特定数据的列的名称

时间:2012-01-11 09:56:19

标签: sql-server-2005

我有五列数据类型int。我已经在主键的基础上选择了行,但现在在这一行中我想选择名称的特定列,其值小于结果列的某个int值。

USE [MedicalLabDB]

GO

/****** Object: Table [dbo].[Advance_Sub_Tests] Script Date: 01/11/2012 15:33:11 ******/
SET ANSI_NULLS ON GO
SET QUOTED_IDENTIFIER ON GO

CREATE TABLE [dbo].[Advance_Sub_Tests]
  (
     [Advance_Sub_Test_ID]           [INT] IDENTITY(1, 1) NOT NULL,
     [Sub_Test_ID]                   [INT] NULL,
     [L_Bound_M_LessThan_First_Age ] [FLOAT] NULL,
     [U_Bound_M_LessThan_First_Age ] [FLOAT] NULL,
     [L_Bound_M_LessThan_Second_Age] [FLOAT] NULL,
     [U_Bound_M_LessThan_Second_Age] [FLOAT] NULL,
     [L_Bound_M_LessThan_Third_Age]  [FLOAT] NULL,
     [U_Bound_M_LessThan_Third_Age]  [FLOAT] NULL,
     [L_Bound_M_LessThan_Fourth_Age] [FLOAT] NULL,
     [U_Bound_M_LessThan_Fourth_Age] [FLOAT] NULL,
     [L_Bound_M_LessThan_Fifth_Age]  [FLOAT] NULL,
     [U_Bound_M_LessThan_Fifth_Age]  [FLOAT] NULL,
     [L_Bound_F_LessThan_First_Age]  [FLOAT] NULL,
     [U_Bound_F_LessThan_First_Age]  [FLOAT] NULL,
     [L_Bound_F_LessThan_Second_Age] [FLOAT] NULL,
     [U_Bound_F_LessThan_Second_Age] [FLOAT] NULL,
     [L_Bound_F_LessThan_Third_Age]  [FLOAT] NULL,
     [U_Bound_F_LessThan_Third_Age]  [FLOAT] NULL,
     [L_Bound_F_LessThan_Fourth_Age] [FLOAT] NULL,
     [U_Bound_F_LessThan_Fourth_Age] [FLOAT] NULL,
     [L_Bound_F_LessThan_Fifth_Age]  [FLOAT] NULL,
     [U_Bound_F_LessThan_Fifth_Age]  [FLOAT] NULL,
     [First_Age]                     [INT] NULL,
     [Second_Age]                    [INT] NULL,
     [Third_Age]                     [INT] NULL,
     [Fourth_Age]                    [INT] NULL,
     [Fifth_Age]                     [INT] NULL,
     [Test_Active]                   [BIT] NULL,
     [Version]                       [TIMESTAMP] NULL,
     CONSTRAINT [PK_Advance_Sub_Test_1] PRIMARY KEY CLUSTERED (
     [Advance_Sub_Test_ID] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
  )
ON [PRIMARY]  

我有那个表我想选择列名(在第一个年龄,第二个年龄,第三个年龄,第四个年龄,第五个年龄),其值假设&lt; 20(我已经选择了一个特定的行)< / p>

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么你想要一个列名。

试试这个:

select top(1) Age.ColumnName
from Advance_Sub_Tests as AST
  cross apply (
               select 1, 'First_Age',  AST.First_Age  union all
               select 2, 'Second_Age', AST.Second_Age union all
               select 3, 'Third_Age',  AST.Third_Age  union all
               select 4, 'Fourth_Age', AST.Fourth_Age union all
               select 5, 'Fifth_Age',  AST.Fifth_Age
              ) as Age(Sortorder, ColumnName, ColumnValue)
where AST.Advance_Sub_Test_ID = 1 and 
      Age.ColumnValue < 20
order by Age.Sortorder