0

我有一个问题,我无法转换成 sql 假设我有 2 个表 table1 和 table2,这样 table1 的 3 列(P,L,T)代表传输状态之前

P1 L1 t1
P1 L1 t2
P1 L2 t3
P2 L5 t4
P2 L5 t5
P2 L6 t6

表 2 的 3 列 (P, L, T) 表示转移后

P1 L3 t1
P1 L3 t2
P1 L4 t3 
P2 L15 t4
P2 L16 t5
P2 L16 t6

table1 和 table2 之间的唯一区别是 L 列。我们将有相同的 P 和 T 列。我想选择 p 使得属于同一个旧 L 的 T 仍然属于同一个新 L,其中 T 的计数按 L > 1 分组。

**Case** (table1)t1,t2 At L1(old L) and (Table2)t1, t2 At L3(new L). Count of T grouped by L =2  and t1, t2 belong to same L group then return P.

**Case** table1: t3 at L2 and table2: t3 at L4. Count of T grouped by L =1 then ignore P.

**Case** (table1)t4,t5 At L5(old L) and (Table2)t4, t5 At L15 and L16(new L). Count of T grouped by L =2  but t4, t5 belong to different L group then ignore P.

我需要按 L 比较 count(T) 和 Ts 组并返回 P 有什么想法吗?

4

2 回答 2

0
于 2012-07-31T05:35:36.460 回答
0

我通过创建一个包含无效行的表变量解决了这个问题,P,T 的表变量并从 table1 join table2 group by table1.p 中选择,table1.L

Drop table table1
Drop table Table2
create table table1
(
P bigint, L bigINt, T BigInt
)
create table table2
(
P bigint, L bigINt, T BigInt
)
Declare @Invalid_Ps table(P BIGINT, L BIGINT)
Insert INTO @Invalid_Ps (P, L)
Select a.Tbl1P ,a.Tbl1L
FROM
(Select tbl1.P as Tbl1P, tbl1.L as Tbl1L,Tbl2.L as Tbl2L , Tbl1.T as Tbl1T
from Table1 as tbl1 Join Table2 as tbl2
ON tbl1.P = Tbl2.P
Group By tbl1.P, tbl1.L,Tbl2.L, Tbl1.T
) a
 GROUp BY a.Tbl1P,a.Tbl1L
Having (SUM(a.Tbl2L) IS NULL OR count(distinct a.Tbl2L) <> 1)
于 2012-07-30T16:47:35.727 回答