-3

我有我的主表 T1,我从中选择许多字段:

ID
1000

我有表 T2:

ID      SERVICE
1000    IPTV
1000    VOIP

我有表 T3:

ID      DEVICE
1000    MODEM
1000    ROUTER
1000    DVC

我想将 T1 与 T2 或 T3 一起加入,它们可以但也可能根本没有值!!!!当它们具有我希望在 SELECT 中具有来自 T2 或 T3 的最大记录数的记录数时。所以在这种情况下,T3 有 3 条记录,这是最大的,我想要 SELECT 中的 3 条记录。(如果 T2 有 3 条记录,如果 T3 有 2 条记录,则为最大值)

但在我的 SELECT 语句中,我有 5 条我不想要的记录。正确的表达方式是什么?我下面的查询返回 5 条记录(我想要 3 条)

select t1.id,t2.service,t3.device
from t1
left outer join T2 on t1.id=t2.id
left outer join T3 on t1.id=t3.id
4

2 回答 2

1
SELECT
    t1.id
  , t2.service
  , t3.device
FROM
        t1
    LEFT JOIN
            ( SELECT
                  ROW_NUMBER() OVER (PARTITION BY id ORDER BY service) AS rn
                , id
                , service
              FROM
                  t2
            ) AS t2
        FULL JOIN 
            ( SELECT
                  ROW_NUMBER() OVER (PARTITION BY id ORDER BY device) AS rn
                , id
                , device
              FROM
                  t3
            ) AS t3
          ON  t3.id = t2.id
          AND t3.rn = t2.rn
      ON COALESCE(t2.id, t3.id) = t1.id ;
于 2012-07-07T19:44:25.960 回答
0

这个要求听起来不正确,但以下应该有效

SELECT T1.*, z2.ID, z2.SERVICE FROM 
(
  SELECT ID, CASE WHEN SUM(INDICATOR) >=0 THEN 1 ELSE -1 END AS INDICATOR FROM
    (
    SELECT ID, SERVICE, 1 AS INDICATOR FROM t2
    UNION ALL
    SELECT ID , DEVICE AS SERVICE , -1 AS INDICATOR FROM t3
    ) z
  GROUP BY ID
) z1
INNER JOIN
(
  SELECT ID, SERVICE, 1 AS INDICATOR FROM t2
  UNION ALL
  SELECT ID , DEVICE AS SERVICE, -1 AS INDICATOR FROM t3
) z2
ON z1.ID = z2.ID AND z1.INDICATOR = z2.INDICATOR
RIGHT JOIN T1 ON T1.ID = Z2.ID
于 2012-07-07T19:29:29.497 回答