SQL查询 - 选择总计大于0的列

时间:2011-05-04 08:13:51

标签: sql sql-server tsql

这是我的SQL查询:

DROP TABLE #tempi
CREATE TABLE #tempi
             (
                          nav1 VARCHAR(50),
                          nav2 INT        ,
                          nav3 INT        ,
                          nav4 INT        ,
                          nav5 INT
             )
INSERT
INTO   #tempi
SELECT   COALESCE(CAST(machinename AS VARCHAR(28)), 'Grand Total:')               AS machinename        ,
         SUM(CASE WHEN vfrm.job_id = '1001' THEN DATEDIFF(mi, 0, total_time) END) AS crate_small        ,
         SUM(CASE WHEN vfrm.job_id = '1002' THEN DATEDIFF(mi, 0, total_time) END) AS crate_medium       ,
         SUM(CASE WHEN vfrm.job_id = '1014' THEN DATEDIFF(mi, 0, total_time) END) AS front_air_deflector,
         SUM(CASE WHEN vfrm.job_id = '9999' THEN DATEDIFF(mi, 0, total_time) END) AS no_schedule
FROM     ven_fullreportmaster vfrm
         INNER JOIN ven_descriptionmaster vdm
         ON       vdm.description_id = vfrm..description_id
         INNER JOIN ven_machinemaster vm
         ON       vm.machine_id = vfrm..machine_id
WHERE    vfrm.entry_date        = CONVERT(VARCHAR, GETDATE()-7, 105)
         --and  vfrm.shift_id =1
AND      vfrm.is_task_completed = 'Y'
GROUP BY machinename WITH ROLLUP

tempi表中的输出:

nav1    nav2    nav3   nav4   nav5

abc      0:0     0:0     0:0   1:0

def      0:0     1:0     2:0   1:0

ghi      0:0     0:0     0:0   1:0

grand    0:0     1:0     2:0   3:0
 total

我想选择总计大于0的列。如何实现?

1 个答案:

答案 0 :(得分:1)

CREATE TABLE #tempi ( nav1 VARCHAR(50), nav2 INT, nav3 INT, nav4 INT, nav5 INT ) 
INSERT INTO #tempi VALUES('Grand Total:',    0.0,     1.0,     2.0,   3.0) 

DECLARE @dynsql NVARCHAR(MAX)

SELECT @dynsql = ISNULL(@dynsql + ',','') + QUOTENAME(col) FROM #tempi 
UNPIVOT(nav FOR col IN (nav2,nav3,nav4,nav5)) AS unpvt
WHERE  nav1 = 'Grand Total:' AND nav>0

IF(@@ROWCOUNT > 0)
    BEGIN
    SET @dynsql = 'SELECT ' + @dynsql + ' FROM #tempi'
    EXEC(@dynsql)
    END

DROP TABLE #tempi

或者如果您不能使用UNPIVOT ...

DECLARE @dynsql NVARCHAR(MAX)

SELECT @dynsql = CASE WHEN nav2>0 THEN ',nav2' ELSE '' END + 
                 CASE WHEN nav3>0 THEN ',nav3' ELSE '' END +
                 CASE WHEN nav4>0 THEN ',nav4' ELSE '' END +
                 CASE WHEN nav5>0 THEN ',nav5' ELSE '' END
FROM #tempi 
WHERE  nav1 = 'Grand Total:'

IF(LEN(@dynsql) > 0)
    BEGIN
    SET @dynsql = STUFF(@dynsql,1,1,'SELECT ') + ' FROM #tempi'
    EXEC(@dynsql)
    END