如果你只是想學習如何使用循環....
DECLARE @DATA TABLE (
SpotID INT,
EventID INT,
MaxTemp INT
);
DECLARE @NEWDATA TABLE (
SpotID INT,
T30 INT,
T90 INT,
T100 INT
);
DECLARE
@SPOT AS INT,
@T30 AS INT,
@T90 AS INT,
@T100 AS INT;
INSERT INTO @DATA VALUES
(123, 1, 45),
(236, 1, 109),
(69 , 1, 18),
(123, 2, 216),
(236, 2, 29),
(69 , 2, 84),
(123, 3, 91),
(236, 3, 457),
(69 , 3, 280);
DECLARE STATION CURSOR FOR SELECT SpotID FROM @DATA GROUP BY SpotID;
OPEN STATION;
FETCH NEXT FROM STATION INTO @SPOT;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @T30 = 0;
SET @T90 = 0;
SET @T100 = 0;
SELECT
@T30 = SUM(CASE WHEN MaxTemp > 30 AND MaxTemp < 70 THEN 1 ELSE 0 END),
@T90 = SUM(CASE WHEN MaxTemp >= 70 AND MaxTemp < 100 THEN 1 ELSE 0 END),
@T100 = SUM(CASE WHEN MaxTemp >= 100 THEN 1 ELSE 0 END)
FROM @DATA WHERE SpotID = @SPOT
INSERT INTO @NEWDATA VALUES (@SPOT,@T30,@T90,@T100)
FETCH NEXT FROM STATION INTO @SPOT;
END;
CLOSE STATION;
DEALLOCATE STATION;
SELECT * FROM @NEWDATA
反正我會寫請求的代碼,但這個例子說明如何創建表變量,一個簡單的遊標用於循環,並寫入到加載到新表中的變量的答案中。
很多移動部件,但它可以讓你洞察做循環。
什麼DBMS? Sql Server? MySQL的? – 2014-11-04 22:53:31
對不起,忘記了!這是Sql Server – MikeB 2014-11-04 23:22:12