我有这张桌子:
id akce text x y z a year 61 FF1231-00 Bob NULL NULL 58 NULL 2014 62 FF1231-00 Alice NULL NULL 57 NULL 2014 57 FF1231-00 1/2 SWC 2 20 NULL NULL 2014 58 FF1231-00 1/3 SWC 3 5 NULL NULL 2014 59 FF1231-00 Jim NULL NULL 57 NULL 2014
现在我正在尝试实现查找在SUM匹配时列z
不为NULL的结果数
table.id = table.z WHERE table.z is NOT NULL
id akce text x y z a year 57 FF1231-00 1/2 SWC 2 20 NULL 2 2014 58 FF1231-00 1/3 SWC 3 5 NULL 1 2014
我试着做以下
SELECT T1.id, T1.text, T1.z, T1.akce, T2.[text], (SELECT COUNT(T1.z) where T1.z IS NOT NULL Group by T1.z)
FROM ubytov T1
LEFT OUTER JOIN ubytov T2
ON T1.z = T2.id
WHERE T1.akce='FF1231-00' AND T1.z IS NULL
但得到了这个例外:
每个GROUP BY表达式必须至少包含一个不是外部引用的列。
你能帮助我实现这个结果吗?
提前致谢并感谢您的时间。
编辑: 根据Fabio回答的这个查询给了我想要的结果:
SELECT t.id
, t.akce
, t.text
, t.x
, t.y
, t.z
, qnt.Quantity
FROM ubytov t
OUTER APPLY (SELECT COUNT(q.z) AS Quantity FROM Ubytov
q WHERE q.z = t.id) qnt WHERE t.z is NULL
答案 0 :(得分:2)
根据我的理解,您想知道从ID
列中找到多少z
试试CROSS APPLY
(来自SQL Fiddle sample的查询)
SELECT t.ID
, t.Akce
, t.x
, t.y
, t.z
, qnt.Quantity
FROM Test t
OUTER APPLY (SELECT COUNT(q.ID) AS Quantity FROM Test q WHERE q.z = t.ID) qnt
如果要从结果中删除Quantity = 0
行,请执行
然后将OUTER APPLY
更改为CROSS APPLY
答案 1 :(得分:0)
试试这个:
SELECT T1.id, T1.text, T1.z, T1.akce, T2.[text],
(SELECT COUNT(T3.z) FROM ubytov T3 where T3.z IS NOT NULL)
FROM ubytov T1
LEFT OUTER JOIN ubytov T2
ON T1.z = T2.id
WHERE T1.akce='FF1231-00' AND T1.z IS NULL