我有以下选择声明......
SELECT ROW_NUMBER() OVER(order by cola) as [id], cola
FROM Table1
这构成了我想要作为@var插入的所有值的表格,现在它可以工作但我必须每次都指定@var ...
SELECT @var AS [Cola], (
SELECT COUNT(*)
FROM vwTableA AS Z
WHERE Cola = COALESCE(@var,Cola)
AND NOT EXISTS (
SELECT *
FROM TableB
WHERE Colb = Z.Colb
)
) AS [NewCol1],
(
SELECT COUNT(*)
FROM vwTableB AS Y
INNER JOIN TableC AS C
ON Y.Colc = C.Colc
WHERE Y.Cola = @var
) AS [NewCol2],
(
SELECT COUNT(*)
FROM vwTableC AS X
INNER JOIN TableD AS D
ON X.Colc = D.Colc
WHERE X.Cola = @var
) AS [NewCol3]
所以我想要通过我显示的第一个Select / Table中的“cola”的所有值来运行第二次选择,而不是必须指定@var并且每次只返回一行。我怎样才能做到这一点?
答案 0 :(得分:2)
如果您使用Common Table Expression CTE,您可以使用它来加入您的其他声明
with var as
( SELECT ROW_NUMBER() OVER(order by cola) as [id], cola
FROM Table1)
SELECT var.id AS [Cola], (
SELECT COUNT(*)
FROM vwTableA AS Z
WHERE Cola = COALESCE(var.id,Cola)
AND NOT EXISTS (
SELECT *
FROM TableB
WHERE Colb = Z.Colb
)
) AS [NewCol1],
(
SELECT COUNT(*)
FROM vwTableB AS Y
INNER JOIN TableC AS C
ON Y.Colc = C.Colc
WHERE Y.Cola = var.id
) AS [NewCol2],
(
SELECT COUNT(*)
FROM vwTableC AS X
INNER JOIN TableD AS D
ON X.Colc = D.Colc
WHERE X.Cola = var.id
) AS [NewCol3]
FROM var