动态创建视图表

时间:2014-10-03 18:04:47

标签: sql sql-server

我有2个名为Circuits and Detections的表 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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

除了在@Tab Alleman的回答中使用SUM之外,您还可以使用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