SQL - 删除(消除)没有数据的列

时间:2018-04-16 20:49:22

标签: sql-server null

我不知道; 在SQl中,是否可以不带有没有数据(或零值)的列?

Select * from PLAYER_TABLE where PLAYER_NAME='cagri'

它只带了一排。因为PLAYER_NAME只有一名玩家是“cagri”。

例如统计数据有30列。 Score-Rebound-PlayedMinutes-Fauls等......

Score=2
Rebound=0
PlayedMinutes=2
Fauls=0

我想在调用我的查询时只看到[Score]和[PlayedMinutes]列。

有可能吗?

2 个答案:

答案 0 :(得分:1)

您可以在stored procedure in SQL

上使用此逻辑

DDL

create table usr_testtable 
(player varchar(30),col1 float, col2 float, col3 float, col4 float)

insert into usr_testtable 
values ('Jordan',10,20,3,0)

转换为存储过程

declare @playername varchar(30) = 'Jordan'   --- pass this value

declare @ctr smallint = 2  -- start from ordinal 2
declare @maxctr smallint = (SELECT max(ORDINAL_POSITION)
                            FROM INFORMATION_SCHEMA.COLUMNS
                            WHERE TABLE_NAME = 'usr_testTable')

declare @columns varchar(max) = ''
declare @columnswithvalues varchar(max) = ''

declare @coltocheck varchar(30)


declare @mysql nvarchar(max)
declare @coloutput varchar(30) 

while @ctr <= @maxctr  
    begin

            SELECT @coltocheck = COLUMN_NAME
                            FROM INFORMATION_SCHEMA.COLUMNS
                            WHERE TABLE_NAME = 'usr_testTable'
                            and ORDINAL_POSITION = @ctr


          set @mysql = N'select @output = ' + @coltocheck + ' from usr_testTable where player =''' + @playername + ''' and cast(' + @coltocheck +' as float) > 0'

          EXECUTE sp_executesql    @mysql,N'@output int OUTPUT',@output = @coloutput OUTPUT;



          if @coloutput > 0 
             begin
              set @columns = coalesce(@columns + ',' + @coltocheck,@columns)
              set @columnswithvalues =  coalesce(@columnswithvalues + char(13) + char(10) + @coltocheck + ' : '  + @coloutput,@columnswithvalues)  --- text form
            end

          set @coloutput = ''

          set @ctr= @ctr + 1

    end

-- final result in table format

set @mysql = N'select player' + @columns + ' from usr_testTable where player =''' + @playername + ''' '
EXECUTE sp_executesql @mysql

-- final result in text format appended with columnname
select @columnswithvalues    -- format to display in text

答案 1 :(得分:0)

首先创建动态SQL以选择除{Sqrt[dy^2 E^( 2 Sqrt[1/y] - (2 x)/y) (-(1/2) (1/y)^(3/2) + x/y^2)^2 + ( dx^2 E^(2 Sqrt[1/y] - (2 x)/y))/y^2], 2.05599, 0.0457029} 之外的表PLAYER_TABLE中的所有列名称,然后将PLAYER_NAME中的数据从表格PLAYER_TABLE中取消,然后您可以搜索值&lt ;&GT; 0并在第二个动态SQL中选择此列。

PLAYER_TABLE1