2016-02-22 139 views
2

任何TSQL高手可以帮我以下的问题:TSQL查询

我有一个名为“数据”表的数据库,该表有以下栏目:

ID| RunId| AccountStaf_1 |AccountStaf_2 |AccountNr| 
------------------------------------------- 

该表将包含以下数据:

ID| RundId| AccountStaf_1 | AccountStaf_2 | AccountNr| 
---------------------------------------------- 
1 | A | xxx   |NULL   | 123456 | 
2 | A | yyy   |NULL   | 123456 | 
3 | A |    | zzz   | 123456 | 
4 | A | fff   | NULL   | 123444 | 
5 | B | NULL   | hhh   | 666666 | 
6 | B | bbb   | NULL   | 666666 | 

谁能帮我定义TSQL查询查找所有具有在相同的“runid为”一个AccountStaf_1和AccountStaf_2的accountNr。

结果的结果应该是这样的:

ID| RunId| AccountStaf_1 | AccountStaf_2 | AccountNr| 
---------------------------------------------- 
1 | A | xxx   |NULL   | 123456 | 
2 | A | yyy   |NULL   | 123456 | 
3 | A |    | zzz   | 123456 | 
5 | B | NULL   | hhh   | 666666 | 
6 | B | bbb   | NULL   | 666666 | 

例如,如果你说“哪里的runid = A”,结果的结果应该是这样的:

ID| RunId| AccountStaf_1 | AccountStaf_2 | AccountNr| 
---------------------------------------------- 
1 | A | xxx   |NULL   | 123456 | 
2 | A | yyy   |NULL   | 123456 | 
3 | A |    | zzz   | 123456 | 

我明白任何帮助你可以提供。

+0

请编辑你的问题,并显示你想要的输出。 –

+0

有一些错误,所以我将描述更改为所需的问题。 – Balatharan

回答

1

如果你想,如果有两个独特的AccountStaff无论返回的结果他们在AccountStaf_1或AccountStaf_2字段中,则可以使用UNION组合这两个字段,然后计算UNIQUE值。如果大于1,则在RunId和AccountNr字段上INNER JOIN。

;WITH AccountStaff AS (
    SELECT RunId, AccountStaf_1 AS AccountStaff, AccountNr 
    FROM Data 
    WHERE AccountStaf_1 IS NOT NULL 
UNION 
    SELECT RunId, AccountStaf_2 AS AccountStaff, AccountNr 
    FROM Data 
    WHERE AccountStaf_2 IS NOT NULL 
), 
AccountList AS (
    SELECT RunID, AccountNr 
    FROM AccountStaff 
    GROUP BY RunID, AccountNr 
    HAVING COUNT(DISTINCT AccountStaff) > 1 
) 
SELECT Data.ID, Data.RunId, Data.AccountStaf_1, Data.AccountStaf_2, Data.AccountNr 
FROM Data INNER JOIN AccountList 
    ON Data.RunId = AccountList.runId AND Data.AccountNr = AccountList.AccountNr 
+0

嗨,Brian,我试过SQl,得到的结果与Thomas相同,但我也希望SQl返回行,例如,两个不同的AccountStaf_1拥有相同的AccountNr。我试过没有运气..得到不同的结果.. – Balatharan

+0

我修改了SQL来适应这个额外的要求。 –

+0

嗨,布莱恩,非常感谢..看来,我现在得到所需的结果.. – Balatharan

0

它被称为自连接。

select yourFields 
from data d1 join data d2 on d1.AccountNR = d2.AccountNR 
where d1.id <> d2.id 
+0

这里没有必要加入 – sagi

+0

我很想看到没有答案的答案。 –

+0

有一些错误,所以我将描述更改为所需的问题。 – Balatharan

1

您可以将数据分组通过的runid和AccountNr和使用集合,看看你的列中包含的任何值:

WITH 
    Accounts AS 
     (
     SELECT 
       RunId, 
       AccountNr 
      FROM 
       Data 
      WHERE 
       RunId = 'A' 
      GROUP BY 
       RunId, 
       AccountNr 
      HAVING 
       MAX(AccountStaf_1) IS NOT NULL 
       AND MAX(AccountStaf_2) IS NOT NULL 

    ) 
SELECT 
     D.ID, 
     D.RunId, 
     D.AccountStaf_1, 
     D.AccountStaf_2, 
     D.AccountNr 
    FROM 
     Data D 
     INNER JOIN Accounts A 
     ON A.AccountNr = D.AccountNr 
      AND A.RunId = D.RunId; 
+0

这个SQL给了我想要的结果...非常感谢。 – Balatharan

+0

嗨,托马斯,我想知道这个SQL是否也返回行,例如两个不同的AccountStaf_1拥有相同的AccountNr。我试图改变SQl没有运气..? – Balatharan