左外连接计数来自不同表的行减去值不同的行

时间:2013-12-27 10:31:15

标签: sql sql-server

您好我有以下SQL查询

SELECT K.name AS Name, K.surname AS Surname, U1.akce AS Event, 
U2.[text] AS [Scheme], U1.[text]  AS [Registered under>], 
( U1.x - (
    SELECT Count(K.ubytov)
    FROM klient
    WHERE ubytov = U2.[text]) ) AS [Free space]
      FROM klient K
      INNER JOIN ubytov U1 ON U1.[text] = K.ubytov
      LEFT OUTER JOIN ubytov U2 ON U1.z = U2.id WHERE U1.akce = '140012-02'
    ORDER BY U1.[text]

我正在尝试实现列Free space中的那个(来自ubytov.x的值匹配U1.z = U2.id) - (表klient中在U1中具有相同值的总行数)。 [文本] = K.ubytov)

在表klientubytov中,我的值与ubytov.text和ubytov.z匹配。我的值与不同行中的ubytov.x相匹配。

有人会帮我解决这个问题吗?

感谢您的时间。

一个例子:

表klient

ID_K ubytov

1   RoomOwner 

2   RoomOwner 

表ubytov

id text x z 

1 roomType1 2 NULL

2 RoomOwner NULL 1

期望的输出:

Name Surname Event Scheme Registered under: Free space

Nam1 Surname1 Even1 Scheme1 RoomOwnerName  0 // (because 2 counts from klient) - (roomType1 x)

1 个答案:

答案 0 :(得分:1)

虽然由于缺少列而不太清楚。 我尝试使用CTE表达式构建所需的查询。 这是sqlfiddle代码。 让我知道,如果这是你正在寻找的。

   create table klient
   (
     id_k int,
     ubytov varchar(25)
   )
   go

   create table ubytov
   (
     id int,
     text varchar(25),
     x int null,
     z int null
   )
   go

   insert into klient(id_k, ubytov)
   select 1, 'RoomOwner'
   union select 2, 'RoomOwner'
   go

   insert into ubytov(id, text, x, z)
   select 1, 'roomType1', 2, null
   union select 2, 'RoomOwner', null, 1
   go       

   ;WITH cte_klint_counts_by_ubytov
   AS
   (
      SELECT
         ubytov,
         Count(ubytov) AS ubytovCount
       FROM klient
       GROUP BY ubytov
   )
   SELECT
     U2.[text] AS [Scheme],
     U1.[text] AS [Registered under>],
     (isnull(U1.x, 0) - isnull(c.ubytovCount, 0)) AS [Free space]
   FROM
     klient K
     INNER JOIN ubytov U1 ON U1.[text] = K.ubytov
     LEFT OUTER JOIN ubytov U2 ON U1.z = U2.id
     LEFT OUTER JOIN cte_klint_counts_by_ubytov c ON c.ubytov = U2.[text]
   ORDER BY u1.[text]