我有两张表格,其中包含来自不同温度传感器的数据:
表1
_TimeStamp温度
2009-12-20 11:59:56.2 10.1
2009-12-20 11:59:56.3 10.2
2009-12-20 11:59:56.4 11.0
2009-12-20 11:59:56.5 Null
表2
_TimeStamp温度
2009-12-20 11:59:56.2 10.5
2009-12-20 11:59:56.5 9.8
2009-12-20 11:59:56.7 12.0
2009-12-20 11:59:56.9 10.0
我想计算两个温度传感器中的任何一个进行非空测量的记录数。对于上面的示例,计数为6,但每个表中实际上有864000个左右的记录 我知道以下SQL Server查询是错误的,但您可以帮忙纠正吗?
(SELECT DISTINCT COUNT(_TimeStamp) FROM Table1) UNION (SELECT DISTINCT COUNT(_TimeStamp) FROM Table2)
答案 0 :(得分:4)
看看这个
DECLARE @Table1 TABLE(
_TimeStamp DATETIME,
Temperature FLOAT
)
DECLARE @Table2 TABLE(
_TimeStamp DATETIME,
Temperature FLOAT
)
INSERT INTO @Table1 SELECT '2009-12-20 11:59:56.2',10.1
INSERT INTO @Table1 SELECT '2009-12-20 11:59:56.3',10.2
INSERT INTO @Table1 SELECT '2009-12-20 11:59:56.4',11.0
INSERT INTO @Table1 SELECT '2009-12-20 11:59:56.5',Null
INSERT INTO @Table2 SELECT '2009-12-20 11:59:56.2',10.5
INSERT INTO @Table2 SELECT '2009-12-20 11:59:56.5',9.8
INSERT INTO @Table2 SELECT '2009-12-20 11:59:56.7',12.0
INSERT INTO @Table2 SELECT '2009-12-20 11:59:56.9',10.0
SELECT COUNT(1) TOTAL
FROM (
SELECT _TimeStamp FROM @Table1 WHERE Temperature IS NOT NULL
UNION
SELECT _TimeStamp FROM @Table2 WHERE Temperature IS NOT NULL
) sub
使用 UNION 而不是 UNION ALL ,您将获得 DISTINCT 时间戳。
答案 1 :(得分:1)
你需要先联合,然后计算。
select count(ts) from
(
select _timestamp as ts
from table1
where temperature is not null
union
select _timestamp
from table2
where temperature is not null
)innerSql
答案 2 :(得分:0)
6的数量来自您的数据?
您的查询也有什么问题?
对我来说似乎很好。你只需删除选择周围的()并命名列。
答案 3 :(得分:0)
你应该可以尝试这样的事情。
SELECT
(
(SELECT DISTINCT COUNT(Id) FROM [Table]) +
(SELECT DISTINCT COUNT(Id) FROM [Table2])
)
这将为您提供两个表中的计数总和。您可以更改子查询以显示您想要的任何条件。