SQL - 在c1中显示一个实例的多个条目,它在c2中具有对应的映射

时间:2015-07-06 09:24:57

标签: sql sql-server sql-server-2008-r2

从三个表中,使用内部联接,我的结果如下所示:

╔═══════╦═══════╦═══════╗
║ t1.c1 ║ t2.c1 ║ t3.c1 ║
╠═══════╬═══════╬═══════╣
║  1a   ║  2a   ║  3a   ║
║  1a   ║  2b   ║  3b   ║
║  1a   ║  2c   ║  3c   ║
║  1b   ║  2a   ║  3a   ║
║  1b   ║  2b   ║  3b   ║
║  1b   ║  2c   ║  3c   ║
╚═══════╩═══════╩═══════╝

是否有可能像下面那样?

╔═══════╦═══════╦═══════╗
║ t1.c1 ║ t2.c1 ║ t3.c1 ║
╠═══════╬═══════╬═══════╣
║  1a   ║  2a   ║  3a   ║
║       ║  2b   ║  3b   ║
║       ║  2c   ║  3c   ║
║  1b   ║  2a   ║  3a   ║
║       ║  2b   ║  3b   ║
║       ║  2c   ║  3c   ║
╚═══════╩═══════╩═══════╝

以下是我使用的代码:

SELECT t1.c1, t2.c1, t3.c1
FROM t1
  INNER JOIN t2
    ON t1.c1=t3.c1
  INNER JOIN t3
    ON t3.c1=t2.c1
WHERE t1.c2 = 'n'
ORDER BY t1.c1 ASC

2 个答案:

答案 0 :(得分:4)

您可以使用CASEROW_NUMBER

WITH Cte AS(
    SELECT *,
        RN = ROW_NUMBER() OVER(PARTITION BY t1c1 ORDER BY (SELECT NULL))
    FROM (
        SELECT 
            t1c1 = t1.c1, 
            t2c1 = t2.c1, 
            t3c1 = t3.c1
        FROM t1
        INNER JOIN t2
            ON t1.c1 = t2.c1
        INNER JOIN t3
            ON t3.c1 = t2.c1
        WHERE t1.c2 = 'n'
    )t
)
SELECT
    t1c1 = CASE WHEN RN = 1 THEN c.t1c1 ELSE '' END,
    c.t2c1,
    c.t3c1
FROM Cte c
ORDER BY c.t1c1

我替换了JOIN上的t2条件。

答案 1 :(得分:4)

我认为你可以使用它:

SELECT     CASE WHEN ROW_NUMBER() OVER (PARTITION BY t1.c1 ORDER BY t2.c1,t3.c1) = 1 THEN t1.c1 END, 
           t2.c1, t3.c1
FROM       t1
CROSS JOIN t2
INNER JOIN t3
ON         t3.c1 = t2.c1
ORDER BY   t1.c1