我有两个表,我无法改变,我试图从两个表中查询和组合一些数据。我理想的做法是在FieldTime2为0时组合省略行,当同一FieldID有两个以上的结果时。如果FieldTime2为0并且只有一个结果,那么我希望显示该行。
你可以计算表2中的FieldID并在count大于1时指定一个数字,或类似的东西?
表1
ID FieldID FieldTime
------------------------
1 A 10
2 B 15
3 C 20
表2
ID FieldID FieldTime2
------------------------
1 A 0
2 A 15
3 B 0
4 C 10
期望的输出:
FieldID FieldTime FieldTime2
------------------------------
A 10 15
B 15 0
C 20 10
我的输出:
FieldID FieldTime FieldTime2
------------------------------
A 10 0
A 10 15
B 15 0
C 20 10
CODE:
SELECT
m.FieldID,
m.FieldTime,
n.FieldTime2,
from Table1 m
Join Table2 n
ON m.FieldID = n.FieldID
Where n.FieldTime > 0
答案 0 :(得分:0)
最简单的解决方案是使用LEFT JOIN查询,如下所示:
SELECT
m.FieldID,
m.FieldTime,
COALESCE(n.FieldTime2, 0) as FieldTime2,
from Table1 m
left Join Table2 n
ON m.FieldID = n.FieldID and n.FieldTime2 > 0
Where n.FieldTime > 0
如果Table2中有多个非零记录且只需要一个,那么查询将会有点复杂:
with n as (
select *,
ROW_NUMBER() OVER(PARTITION BY FieldID ORDER BY FieldTime2 DESC) rn
from Table2
)
SELECT
m.FieldID,
m.FieldTime,
COALESCE(n.FieldTime2, 0) as FieldTime2,
from Table1 m
LEFT Join n
ON m.FieldID = n.FieldID and n.rn = 1
Where n.FieldTime > 0
答案 1 :(得分:0)
根据您的数据样本,并假设只有FieldTime
只有value > 0
,您只需使用MAX()
来解决问题:
SELECT
m.FieldID,
m.FieldTime,
MAX(n.FieldTime2),
FROM Table1 m
JOIN Table2 n ON m.FieldID = n.FieldID
WHERE n.FieldTime > 0
GROUP BY m.FieldID, m.FieldTime
当然,如果可能有多个FieldTime
记录包含value > 0
,此解决方案将无法呈现正确的输出,在这种情况下,您可以使用UNION
来解决问题:
--cases with one record:
SELECT
m.FieldID,
m.FieldTime,
n.FieldTime2
FROM Table1 m
JOIN Table2 n ON m.FieldID = n.FieldID
Where m.FieldID in
(
SELECT FieldID
FROM Table2
HAVING COUNT(FieldID) = 1 -- only one record exists
)
UNION
--cases with multiple records
SELECT
m.FieldID,
m.FieldTime,
n.FieldTime2
FROM Table1 m
JOIN Table2 n ON m.FieldID = n.FieldID
Where m.FieldID not in --make sure we select the rest of the records
(
SELECT FieldID
FROM Table2
HAVING COUNT(FieldID) = 1
) AND n.FieldTime2 > 0 -- make sure to exclude the 0 records.
请注意,这未经过测试,因此请考虑拼写错误,性能不佳或错误。 :)