0

我有一个在下面工作的 T-SQL:


SELECT WP_VTDID AS UTIL_VTDID, 
(SELECT COUNT(WP_ENGINE) FROM WAYPOINTS WHERE (WP_ENGINE = 1) AND (WP_SPEED > 0) AND WP_VTDID='L083') AS UTIL_RUN,
(SELECT COUNT(WP_ENGINE) FROM WAYPOINTS WHERE (WP_ENGINE = 1) AND (WP_SPEED = 0) AND WP_VTDID='L083') AS UTIL_IDLE,
(SELECT COUNT(WP_ENGINE) FROM WAYPOINTS WHERE (WP_ENGINE = 0) AND WP_VTDID='L083') AS UTIL_OFF
FROM WAYPOINTS
WHERE WP_VTDID = 'L083' AND WP_DATETIME BETWEEN '2009-03-13 00:00:00' AND '2009-03-13 23:59:59'
GROUP BY WP_VTDID


但是我有多个WP_VTDID值并且我想获取所有数据,有人可以创建一个适用于多个值的 T-SQL 命令吗?(数据库中已有值)

PS:暂时忽略WP_DATETIME 所以

结果可能是这样的:

---------------------------------
| UTIL_VTDID | 运行 | 空闲 | 关闭 |
---------------------------------
| L083 | 100 | 20 | 0 |
| L084 | 200 | 50 | 10 |
| L085 | 60 | 30 | 50 |
| L086 | 0 | 0 | 100 |
---------------------------------


找到解决方案,感谢Jakob Christensen

SELECT WP_VTDID AS UTIL_VTDID, 
(SELECT COUNT(WP_ENGINE) FROM WAYPOINTS WHERE (WP_ENGINE = 1) AND (WP_SPEED > 0) AND WP_VTDID=t.WP_VTDID) AS UTIL_RUN,
(SELECT COUNT(WP_ENGINE) FROM WAYPOINTS WHERE (WP_ENGINE = 1) AND (WP_SPEED = 0) AND WP_VTDID=t.WP_VTDID) AS UTIL_IDLE,
(SELECT COUNT(WP_ENGINE) FROM WAYPOINTS WHERE (WP_ENGINE = 0) AND WP_VTDID=t.WP_VTDID) AS UTIL_OFF
FROM WAYPOINTS t
WHERE WP_DATETIME BETWEEN '2009-03-13 00:00:00' AND '2009-03-13 23:59:59'
GROUP BY WP_VTDID

谢谢,
德尔斯

4

2 回答 2

2

您想在航点表上加入嵌套的 SQL 语句。

这是未经测试的,但看看我在这里做了什么:

SELECT 
     WAYPOINTS.WP_VTDID AS UTIL_VTDID, 
     COUNT(UTIL_RUN.WP_ENGINE) AS UTIL_RUN
FROM WAYPOINTS
JOIN WAYPOINTS  UTIL_RUN ON
    WAYPOINTS.PKEY=UTIL_RUN.PKEY
AND (UTIL_RUN.WP_ENGINE = 1) AND (UTIL_RUN.WP_SPEED > 0)
WHERE WAYPOINTS.WP_DATETIME BETWEEN '2009-03-13 00:00:00' AND '2009-03-13 23:59:59'
GROUP BY WAYPOINTS.WP_VTDID

只需加入其他价值观。

并将 pkey 替换为您的主键字段。

于 2009-03-13T09:14:47.540 回答
2

这可以解决问题:

SELECT DISTINCT
WP_VTDID AS UTIL_VTDID, 
(
    SELECT COUNT(WP_ENGINE) 
    FROM WAYPOINTS 
    WHERE (WP_ENGINE = 1) 
    AND (WP_SPEED > 0) 
    AND WP_VTDID = t.WP_VTDID
) AS UTIL_RUN,
(
    SELECT COUNT(WP_ENGINE) 
    FROM WAYPOINTS 
    WHERE (WP_ENGINE = 1) 
    AND (WP_SPEED = 0) 
    AND WP_VTDID = t.WP_VTDID
) AS UTIL_IDLE,
(
    SELECT COUNT(WP_ENGINE) 
    FROM WAYPOINTS 
    WHERE (WP_ENGINE = 0) 
    AND WP_VTDID = t.WP_VTDID
) AS UTIL_OFF
FROM WAYPOINTS t
于 2009-03-13T09:17:05.320 回答