2011-05-04 63 views
1

這裏是我的SQL查詢中列:SQL查詢 - 選擇其總計大於0

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.如何實現它?

+0

動態地更改列清單需要動態SQL。如果沒有總計> 0的這樣的列,會發生什麼? – 2011-05-04 10:06:49

+0

有大約40個工作列..和15個機器(行)..所以至少一列將大於0 ..所有列都沒有機會爲零:) – navbingo 2011-05-04 10:13:10

+0

plz幫我寫出一個動態查詢爲它..我desperatly searchng它... – navbingo 2011-05-04 10:13:41

回答

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 
+0

嗨馬丁,我得到一個錯誤.. 156,15級,狀態1,第4行 關鍵字'FOR'附近的語法不正確。 ,我剛剛複製你的代碼,並在sql中執行.. – navbingo 2011-05-04 10:26:20

+0

@navbingo - 你在SQL Server 2000或什麼? – 2011-05-04 10:31:10

+0

@ martin - 我在sql server 2008中工作 – navbingo 2011-05-04 10:36:15