简体   繁体   English

SQL交叉应用计数

[英]SQL Cross Apply Count

I'm trying to use CROSS APPLY in SQL, but only want to use the results of the call if the returned row count is greater than 1. 我正在尝试在SQL中使用CROSS APPLY ,但只想在返回的行数大于1的情况下使用调用结果。

I have the following SQL: 我有以下SQL:

INSERT INTO    @dest (val1, val2, val3)
SELECT         t2.crossVal, t2.crossVal2, t1.tempVal
FROM        @tempTable t1
CROSS APPLY    dbo.TableValuedFunction(t1.IDColumn) t2

The CROSS APPLY returns multiple rows in some cases, but in the vast majority returns one row (as all @tempTable rows have a corresponding result from the function). 在某些情况下, CROSS APPLY返回多行,但绝大多数返回一行(因为所有@tempTable行都具有该函数的相应结果)。 I'm interesting in only inserting those that have multiple corresponding results from the CROSS APPLY . 我只将那些具有从多个相应的结果很有趣CROSS APPLY

I'm trying to avoid inserting all then doing a delete afterwards. 我试图避免插入所有内容,然后再进行删除。 Really interested to see if there is any sort of aggregation action I can apply to that statement as it is. 真的很感兴趣,看看是否有任何类型的聚合操作可以按原样应用于该语句。

Any ideas? 有任何想法吗?

Edit: in response to SQLMenace's answer. 编辑:响应SQLMenace的答案。 I am getting the following results where the left column is tempVal, the middle column is crossVal, the right column is crossVal2: 我得到以下结果,其中左列是tempVal,中间列是crossVal,右列是crossVal2:

a : 1 : z0

b : 1 : z0

a : 2 : z1

b : 2 : z1

c : 1 : z0

d : 1 : z0

I want to ditch the rows "c : 1 : z0" and "d : 1 : z0". 我想抛弃行“ c:1:z0”和“ d:1:z0”。 Also, it may affect the groupings so I will mention this, my final query has two columns returned from the function and one from the temp table. 另外,它可能会影响分组,因此我将提及这一点,我的最终查询具有从函数返回的两列和从临时表返回的两列。

The end query is basically counting the parents of the tempTable row, where there is more than one parent (returned as a table from the function) I want to do the insert and record the order of the parent (again returned from the function). 结束查询基本上是在计算tempTable行的父级,其中有多个父级(从函数返回为表),我想进行插入并记录父级的顺序(再次从函数返回)。 crossVal is the parent ID and crossVal2 is the order as an int. crossVal是父ID,而crossVal2是作为整数的订单。

try this 尝试这个

INSERT INTO    @dest (val1, val2)
SELECT         t2.crossVal, t1.tempVal
FROM           @tempTable t1
CROSS APPLY    dbo.TableValuedFunction(t1.IDColumn) t2
GROUP BY t2.crossVal, t1.tempVal
HAVING COUNT(*) > 1

Since you want to group by the number of rows returned by the cross aply, I would only put the one expression into your group by. 由于您想按交叉返回的行数进行分组,因此我只将一个表达式放入分组依据。 That was why you were getting 6 rows instead of 4: 这就是为什么您得到6行而不是4行的原因:

INSERT INTO    @dest (val1, val2)
SELECT         t2.crossVal, t1.tempVal
FROM           @tempTable t1
CROSS APPLY    dbo.TableValuedFunction(t1.IDColumn) t2
GROUP BY t2.crossVal
HAVING COUNT(*) > 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM