我有一个问题,我无法转换为sql 假设我有2个表table1和table2这样 在转移状态之前表示的3列(P,L,T)的table1
P1 L1 t1
P1 L1 t2
P1 L2 t3
P2 L5 t4
P2 L5 t5
P2 L6 t6
转移后代表的3列(P,L,T)的表2
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的Ts仍然属于相同的新L,其中Ts的计数由L> 1组成。 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.
我需要将count(T)和Ts组比较为L并返回P. 任何想法??
答案 0 :(得分:0)
我通过创建包含无效行的表变量来解决此问题 P,T的表变量,并从table1.p,table1.L
中选择table1 join table2 groupDrop 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)
答案 1 :(得分:0)
我仍然不确定我是否理解整个要求,但这是您可以选择每个T
和{{1}的P
值的L
个值的行}:
WITH counted AS (
SELECT
*,
cnt = COUNT(*) OVER (PARTITION BY P, L)
FROM table1
)
SELECT P, L, T
FROM counted
WHERE cnt > 1
;
然后,根据您的帖子,table2
'将具有相同的P和T列',并且根据您的评论,'T是唯一的P',您可以将上述查询的结果集合加到table2
列和P
列上的T
。这样,您就可以找出L
中哪些table1
值更改为L
中的table2
值:
WITH counted AS (
SELECT
*,
cnt = COUNT(*) OVER (PARTITION BY P, L)
FROM Table1
)
SELECT
t1.P,
t1.L AS OldL,
t2.L AS NewL,
t1.T
FROM counted t1
INNER JOIN table2 t2 ON t1.P = t2.P AND t1.T = t2.T
WHERE t1.cnt > 1
;