2014-10-03 235 views
0

我有2個表名爲Circuits and Detections Circuits表包含所有可能電路的記錄。 檢測表包含Circuits表中電路檢測的記錄。 我想創建一個包含電路列表和每個特定電路的每種類型的檢測計數的視圖。 我想出瞭如下代碼,但它不工作動態創建視圖表

CREATE VIEW Result 
AS 

declare @circuitId INT 
declare my_cursor Cursor for 
SELECT circuitId from Circuits 

OPEN my_cursor 

FETCH NEXT FROM my_cursor INTO @circuitId 

WHILE @@FETCH_STATUS = 0 
BEGIN 
SELECT @circuitId as CircuitId , 
(SELECT COUNT(*) AS AliveCount FROM dbo.Detections WHERE dbo.Detections.circuitId = @circuitId AND dbo.detections.health = 'Alive') AS Alive, 
(SELECT COUNT(*) AS DeadCount FROM dbo.Detections WHERE dbo.Detections.circuitId = @circuitId AND  dbo.detections.health = 'Dead') AS Dead 
FETCH NEXT FROM my_cursor into @circuitId 
END 
CLOSE my_cursor 
DEALLOCATE my_cursor 

我不知道是否有可能在這種情況下使用的視圖。任何建議都非常感謝。謝謝。

回答

2

不,您不能在視圖中使用遊標。但我認爲你可以這樣做:

CREATE VIEW Result 
AS 

SELECT 
    c.circuitId 
, SUM(CASE WHEN d.health='Alive' THEN 1 ELSE 0 END) AS Alive 
, SUM(CASE WHEN d.health='Dead' THEN 1 ELSE 0 END) AS Dead 
FROM Circuits c 
LEFT OUTER JOIN dbo.Detections d 
    ON d.circuitId=c.circuitId 
GROUP BY c.circuitId 
+0

工作十分感謝。 – stoney78us 2014-10-03 18:23:39

0

除了使用SUM在@tab Alleman的回答表明,你也可以使用COUNT如下

CREATE VIEW Result 
AS 

SELECT 
    c.circuitId, 
    COUNT(CASE WHEN d.health = 'Alive' THEN 'Alive' ELSE NULL END) AS Alive, 
    COUNT(CASE WHEN d.health = 'Dead' THEN 'Dead' ELSE NULL END) AS Dead 
FROM Circuits c 
LEFT JOIN Detections d 
    ON d.circuitId = c.circuitId 
GROUP BY c.circuitId