Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TSQL:如何编写此查询?_Sql_Sql Server_Tsql - Fatal编程技术网

TSQL:如何编写此查询?

TSQL:如何编写此查询?,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个查询,返回的结果集如下所示: A | B --------------------- 1 | a 2 | a 1 | b 1 | c 3 | d WITH sampledata (A, B) AS ( SELECT 1, 'a' UNION ALL SELECT 2, 'a' UNION ALL SELECT 1, 'b' UNION ALL SELECT 1, 'c' UNION ALL SE

我有一个查询,返回的结果集如下所示:

A   |   B
---------------------
1   |   a
2   |   a
1   |   b
1   |   c
3   |   d
WITH
  sampledata (A, B) AS (
    SELECT 1, 'a' UNION ALL
    SELECT 2, 'a' UNION ALL
    SELECT 1, 'b' UNION ALL
    SELECT 1, 'c' UNION ALL
    SELECT 3, 'd'
  ),
  counted AS (
    SELECT
      A,
      B,
      COUNT(*) OVER (PARTITION BY B) B_count
    FROM sampledata
  )
SELECT
  COUNT(*)
FROM counted
WHERE A = 1
  AND B_count = 1  /* change to "> 1" to get the other result */
A | B
在结果中是唯一的(即只有一个
1 | A
行)

我需要根据这些结果编写两个查询。第一:

给定
a
(比如
1
)的值,计算只有一行的
B
s的数量;在
a
列中使用
1

因此,在上述数据集中,我希望返回值
2
,因为
B
B
c
各只有一行,其中这些行在
a
列中有一个
1
d
将不被计算,因为它对应于
3
,而
a
将不被返回,因为它有一个额外的
2

希望这是有道理的

第二个查询与上述相反

给定
a
(例如
1
)的值,计算具有2行或多行的
B
s的数量,其中一行在
a
列中具有
1

因此,在上面的数据中,id希望返回
1
,因为
B
a
是唯一具有多行的数据,其中一行在a列中具有
1

谢谢

使用:

declare @t table(A int, B char(1))

insert @t values
(1, 'a'),
(2, 'a'),
(1, 'b'),
(1, 'c'),
(3, 'd')

declare @x int = 1

select COUNT(*)
from @t t
where t.A = @x
    and not exists(select 1 from @t t2 where t2.B = t.B and t2.A <> @x)

select COUNT(*)
from @t t
where t.A = @x
    and exists(select 1 from @t t2 where t2.B = t.B and t2.A <> @x)

使用CTE和窗口聚合函数,可以这样做:

A   |   B
---------------------
1   |   a
2   |   a
1   |   b
1   |   c
3   |   d
WITH
  sampledata (A, B) AS (
    SELECT 1, 'a' UNION ALL
    SELECT 2, 'a' UNION ALL
    SELECT 1, 'b' UNION ALL
    SELECT 1, 'c' UNION ALL
    SELECT 3, 'd'
  ),
  counted AS (
    SELECT
      A,
      B,
      COUNT(*) OVER (PARTITION BY B) B_count
    FROM sampledata
  )
SELECT
  COUNT(*)
FROM counted
WHERE A = 1
  AND B_count = 1  /* change to "> 1" to get the other result */

在效率方面,这与基里尔的回答相比如何?我得到了一大堆(成百上千)@AndrewBullock:我想基里尔是怎么说的。半连接(以EXISTS谓词的形式)通常很难被击败,而对于具有分组(这意味着排序,这是昂贵的)的查询就更难了。是的,如果你的表那么大,我可能会使用Kirill的解决方案。如果A和B是唯一标识符,那么这个查询会在一秒钟内运行,因为Kirill在一分钟内还没有返回:s