只选择那些值不是0 | 0的列。 SQL Server 2016

时间:2019-07-01 12:06:14

标签: sql sql-server sql-server-2016

我有一张这样的桌子:

ID, ColA, ColB, ColC, ColD
---------------------------
10,   0,    4,    6,    9
11,   0,    3,    3,    8

当给定列的总和> 0时,我想选择它。因此,查询中的列数根据总数而变化。

任何建议都会很棒。我实际上不知道如何进行,所以到目前为止我还没有任何代码尝试。

4 个答案:

答案 0 :(得分:1)

首先,此请求听起来很奇怪,闻起来很糟糕。

但是,如果您想实现这一点,我会使用动态SQL来做到这一点:

Declare @ShowColA bit
Declare @ShowColB bit
Declare @ShowColC bit
Declare @ShowColD bit
Declare @sqlCommand varchar(max)

IF (SELECT SUM(ColA) FROM yourTable) > 0
    SET @ShowColA = 1
IF (SELECT SUM(ColB) FROM yourTable) > 0
    SET @ShowColB = 1
IF (SELECT SUM(ColC) FROM yourTable) > 0
    SET @ShowColC = 1
IF (SELECT SUM(ColD) FROM yourTable) > 0
    SET @ShowColD = 1

SET @sqlCommand = 'SELECT Id'
IF @ShowColA<> 0 SET @sqlCommand = @sqlCommand + ', ColA'
IF @ShowColB<> 0 SET @sqlCommand = @sqlCommand + ', ColB'
IF @ShowColC<> 0 SET @sqlCommand = @sqlCommand + ', ColC'
IF @ShowColD<> 0 SET @sqlCommand = @sqlCommand + ', ColD'
SET @sqlCommand = @sqlCommand + ' FROM yourTable'

EXEC @sqlCommand

答案 1 :(得分:1)

以下查询应执行您想要的操作:

CREATE TABLE #temp (ID INT, ColA INT, ColB INT, ColC INT, ColD INT)

INSERT INTO #temp VALUES
(10,   0,    4,    6,    9),
(11,   0,    3,    3,    8)

DECLARE @Col VARCHAR(100) = '';

SELECT @Col += ',' + [Col] FROM #temp
UNPIVOT (
Val for Col In ([ColA],[ColB],[ColC],[ColD]))unpiv
GROUP BY Col
HAVING SUM(Val) > 0;

SET @Col = STUFF(@Col,1,1,'');

EXEC ('SELECT [ID],'+@Col+' FROM #temp');

结果如下,

ID  ColB  ColC  ColD
10  4     6     9
11  3     3     8

答案 2 :(得分:0)

我猜表中唯一可能的值是非负数。因此,您可以尝试使用SUM()对列进行求和,如果该列为0,则不要采用该列。

答案 3 :(得分:0)

您可以尝试以下方法:

CREATE TABLE #TEST
(
  ID INT
, COLA INT
, COLB INT
, COLC INT
, COLD INT
);

INSERT INTO #TEST VALUES
(
10,   0,    4,    6,    9
),
(
11,   0,    3,    3,    8
);

BEGIN 

DECLARE @COLLIST AS VARCHAR(100)
DECLARE @RESULT AS INTEGER

SET @COLLIST = ''
SET @RESULT = (SELECT SUM(COLA) FROM #TEST)
IF @RESULT > 0
   SET @COLLIST = 'COLA'
SET @RESULT = (SELECT SUM(COLB) FROM #TEST)
IF @RESULT > 0
   IF @COLLIST <> ''
      SET @COLLIST = @COLLIST + ', '
   SET @COLLIST = @COLLIST + 'COLB'
SET @RESULT = (SELECT SUM(COLC) FROM #TEST)
IF @RESULT > 0
   IF @COLLIST <> ''
      SET @COLLIST = @COLLIST + ', '
   SET @COLLIST = @COLLIST + 'COLC'
SET @RESULT = (SELECT SUM(COLD) FROM #TEST)
IF @RESULT > 0
   IF @COLLIST <> ''
      SET @COLLIST = @COLLIST + ', '
   SET @COLLIST = @COLLIST + 'COLD'   

IF @COLLIST <> ''
   BEGIN
       PRINT ('SELECT ' + @COLLIST + ' FROM #TEST')
       EXEC ('SELECT ID, ' + @COLLIST + ' FROM #TEST')
   END

END

结果:

ID COLB COLC COLD
10  4   6   9
11  3   3   8