T-SQL组检查

时间:2016-05-20 10:14:15

标签: sql sql-server sql-server-2008 tsql sql-server-2012

我有三个表 - Table_1,Table_2和Table_3。这是每个人的样子:

TABLE_1

   ID  | TicketID | Rule  
---------------------------
    1  |    101   | NULL

TABLE_2

    TicketID | Location
---------------------------  
       101   | A
       101   | B

TABLE_3

Location | Rule
--------------------
    A    |  R1
    B    |  R1
    A    |  R2
    B    |  R2
    C    |  R2

我的目标是填充Table_1中的Rule列(它应该是Table_3中Rule列的select distinct)。这个过程应该是:

  • 从Table_1获取TicketID。在TicketID上加入Table_1到Table_2,并获取与该票证相关联的位置。
  • 查找Table_3并检查需要应用的规则。检查需要在组级别。例如,在该示例中,票证101具有位置A,B。表_3具有针对规则R1的A,B,但是具有针对规则R2的A,B,C。正确的规则应该是R1,因为Ticket 101没有为位置C分配。希望这是有道理的。实现这一目标最简单的方法是什么?提前致谢!

4 个答案:

答案 0 :(得分:0)

请尝试以下代码。它在SQL Server 2012中运行良好。

DECLARE @table_1 TABLE
(ID int, TicketID int, [Rule] Varchar(10))

DECLARE @table_2 TABLE
(TicketID int, Location Varchar(10))

DECLARE @table_3 TABLE
(Location Varchar(10),[Rule] Varchar(10))

INSERT @table_1
(ID,TicketID,[Rule])
VALUES
(1,101,NULL)

INSERT @table_2
(TicketID,Location)
VALUES
(101,'A'),
(101,'B')

INSERT @table_3
(Location,[Rule])
VALUES
('A','R1'),
('B','R1'),
('A','R2'),
('B','R2'),
('C','R2')

SELECT DISTINCT [RULE] FROM @table_3 t3 WHERE t3.Location IN
(SELECT t2.Location FROM @table_2 t2 INNER JOIN @table_1 t1 ON t1.TicketID = t2.TicketID)
AND [RULE] NOT IN 
(SELECT t.[RULE] FROM @table_3 t WHERE t.Location NOT IN 
(SELECT t2.Location FROM @table_2 t2 INNER JOIN @table_1 t1 ON t1.TicketID = t2.TicketID))

答案 1 :(得分:0)

尝试这个..

SELECT t1.TicketID
,t2.[Rule]
FROM (SELECT DISTINCT t2.TicketID,[Rule]
FROM @table_3 t3 INNER JOIN 
     @table_2 t2 ON t2.Location = t3.Location) t2
INNER JOIN @table_1 t1 ON t2.TicketID = t1.TicketID

将此select语句与上面声明的表变量

一起使用

答案 2 :(得分:0)

Dim popCus As New PopCustomer()
popCus.StartPosition = FormStartPosition.Manual
popCus.Location = New Point(ctrList.Location)
popCus.Size = New Size(ctrList.Size)
popCus.ShowDialog()

答案 3 :(得分:0)

试试这段代码:

SELECT DISTINCT [RULE] FROM Table_3 t3 WHERE t3.Location IN
(SELECT t2.Location FROM Table_2 t2 INNER JOIN Table_1 t1 ON t1.TicketID = t2.TicketID)
AND [RULE] NOT IN 
(SELECT t.[RULE] FROM Table_3 t WHERE t.Location NOT IN 
(SELECT t2.Location FROM Table_2 t2 INNER JOIN Table_1 t1 ON t1.TicketID = t2.TicketID))