繁体   English   中英

通过SQL检索列

[英]retrieve columns with through sql

这是我的表的一个示例,没有索引,没有主键,没有任何内容,几乎有6000列。

date     col1 col2 col3 ... col6000
jun14     0    .    0       0
may14     1    .    2       2
apr14     1    .    3       1
mar14     1    3    3       0
feb14     1    3    3       5
jan14     1    0    3       8
dec13     1    0    3       1

我想知道,哪一列只有 自2014年4月起。

已编辑

我的预期结果是,在3列示例中,请参见上文,自2014年4月以来,第2列仅包含点

编辑结束

我当时正在考虑换位,但这似乎是没有意义的解决方案。

自昨天以来,我一直在解决该问题,但我没有解决方案。 啊!

谢谢。

编辑 :我的查询将是以下

select * from mytable where date < (input('may14',MONYY5.));

但是,它并没有提供我期望的结果,因为它正在从所有列中检索所有行。 我本来打算换桌子,但这样做并没有带我去任何地方。

编辑结束

我认为用6000列在SQL中没有什么可以做的。

我将整个内容下载到一个CSV文件(您有多少行?),并使用遍历该文件的编程语言编写一些处理代码。

从外观上看,它可以是一次通过(请确保该文件在该日期列之前排序)。

假设我只有3栏。 会更简单吗?

三列,也许

SELECT max(date) FROM the_table WHERE col1 <> '.' HAVING max(date) < 'may14';
SELECT max(date) FROM the_table WHERE col2 <> '.' HAVING max(date) < 'may14';
SELECT max(date) FROM the_table WHERE col3 <> '.' HAVING max(date) < 'may14';

顺便说一句,日期真的看起来像吗? 如果无法以有意义的方式对它们进行排序,那么您将面临另一个大问题。

这是一种动态方法,我假设您的日期列为DateTime格式,结果是所有列的列表,其中仅包含特定时间的点:

if object_id('test') is not null drop table test

create table test
(
[date] datetime, 
col1 nvarchar(1), 
col2 nvarchar(1), 
col3 nvarchar(1), 
col4 nvarchar(1), 
col5 nvarchar(1), 
col6 nvarchar(1), 
col7 nvarchar(1)
)

declare @i int, @cols int, @cmd nvarchar(max)

insert into test values('2014-01-01', 1, 2, 3, 4, 5 ,6 ,7)
insert into test values('2014-02-01', 1, 2, 3, 4, 5 ,6 ,7)
insert into test values('2014-03-01', 1, 2, 3, 4, 5 ,6 ,7)
insert into test values('2014-04-01', 1, 2, 3, 4, 5 ,6 ,7)
insert into test values('2014-05-01', 1, '.', '.', 4, 5 ,6 ,7)
insert into test values('2014-06-01', 1, '.', '.', 4, 5 ,6 ,7)
insert into test values('2014-07-01', 1, '.', '.', 4, 5 ,6 ,7)
insert into test values('2014-08-01', 1, '.', 5, 4, 5 ,6 ,7)


if object_id('tempdb..#chk') is not null drop table #chk 
create table #chk
(
    checkValue int
)

declare @result table
(
    ColList nvarchar(64) 
)

declare @dateFrom datetime, @test cursor, @colName nvarchar(64), @returnValue int 

set @dateFrom = '2014-05-01'

set @test = cursor for 
                select name from syscolumns 
                where id = object_id('test') 
                and name <> 'date' 
                order by colorder 

open @test
fetch next from @test into @colName
while @@fetch_status = 0 
begin
    truncate table #chk
    set @cmd = 'select top 1 1 from test where date >= ''' + convert(varchar(32), @dateFrom) + ''' and ' + @colName + ' <> ''.'''

    insert into #chk exec( @cmd)

    if @@rowcount = 0
        insert into @result values(@colName) 

    fetch next from @test into @colName 
end

select * from @result

如果我误解了您的需求,请纠正我!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM