如何获取包含值> 0的第一列

时间:2011-08-01 06:57:38

标签: sql

如何获取包含值> 0的第一列

Type      Dec 09      Mar 10      Jun 10      Sep 10      Dec 10      Mar 11      Jun 11 
A    (0.07)  (0.11)  0.00    (0.01)  0.10    0.02    0.22 

我想找到上面的数据 1)包含> 0值的第一列 - (例如对于例如ans应该是Jun 10) 2)第一列包含> 0值&下一列也包含> 0值 - (例如,对于例如ans应该是Dec 10)

3 个答案:

答案 0 :(得分:0)

希望(我真的很希望)您的表格如下,并且您因任何原因转换了数据(并且Dec 09列的名称):

---------------
Type     A
---------------
Dec 09   (0.07)
May 10   (0.11)
Jun 10   0.00
Sep 10   (0.01)
Dec 10   0.10
Mar 11   0.02
Jun 11   0.22

MySQL的:

select *
  from table
 where A= 0
 order by type 
limit 0, 2

答案 1 :(得分:0)

在MS SQL Server 2005及更高版本中,您可以使用系统DMVs sys.tables和sys.columns来获取此表的列列表,然后使用cursor进行迭代。这是丑陋的,但工作解决方案。 你可以这样看的列列表:

SELECT sys.columns.name from sys.columns INNER JOIN sys.tables ON sys.columns.object_id 
= sys.tables.object_id
WHERE sys.tables.name='TableName'

答案 2 :(得分:0)

你必须写一个复杂而具体的表达式才能做到这一点。由于您的字段名称中包含数据,因此SQL中没有构造可以轻松查询此数据。

类似的东西,这只是为了获得第一次约会:

select
  Type,
  case
    when [Mar 10] > 0 then [Mar 10]
    when [Mar 11] > 0 then [Mar 11]
    when [Jun 10] > 0 then [Jun 10]
    when [Jun 11] > 0 then [Jun 11]
    when [Sep 10] > 0 then [Sep 10]
    when [Dec 09] > 0 then [Dec 09]
    when [Dec 10] > 0 then [Dec 10]
  end
from TheTable

您应该将数据安排如下:

Type   Date          Value
A      2011-12-09    -0.07
A      2011-05-10    -0.11
A      2011-06-10    0.00
A      2011-09-10    -0.01
A      2011-12-10    0.10
A      2011-03-11    0.02
A      2011-06-11    0.22

然后您可以编写一个不必知道哪些日期的查询。类似的东西:

select x.Type, x.Date, t.Value
from TheTable t
inner join (
  select Type, min(Date) as Date
  from TheTable
  where Value > 0
  group by Type
) x on x.Type = t.Type and x.Date = d.Date