开发者

SQL Cross Apply Count

开发者 https://www.devze.com 2023-01-17 03:07 出处:网络
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.

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.

I have the following 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). I'm interesting in only inserting those that have multiple corresponding results from the 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. I am getting the following results where the left column is tempVal, the middle column is crossVal, the right column is 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". Also, it may affect the groupings so I will mention thi开发者_StackOverflow社区s, 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). crossVal is the parent ID and crossVal2 is the order as an int.


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:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消