[英]count/select query in MS Sql Server 2005
I have a legacy table that contains 'master' records and associated detail records. 我有一个旧表,其中包含“主”记录和相关的详细记录。 Detail records are identified by an addition to the master key of "-nnn".
详细记录通过在主键“ -nnn”上添加来标识。 I need to find master records that have no detail records, tried several variations, and then finally broke it down to simplest elements.
我需要找到没有详细记录的主记录,尝试了几种变体,然后将其分解为最简单的元素。
This works: 这有效:
select (select count(*) from dbo.client as cl2
where cl2.acct_no like (cl1.acct_no + '-%')) as countx, acct_no
from dbo.client as cl1
and displays the expected zero or non-zero results, depending on how many detail records there are. 并显示预期的零或非零结果,具体取决于有多少明细记录。
However, when I try to use the count results to select only the records with zero detail records, like so: 但是,当我尝试使用计数结果仅选择零记录的记录时,如下所示:
select (select count(*) from dbo.client as cl2
where cl2.acct_no like (cl1.acct_no + '-%')) as countx, acct_no
from dbo.client as cl1
where countx = 0
I get an error: "Invalid column name 'countx'" 我收到一个错误:“无效的列名'countx'”
What am I missing here? 我在这里想念什么?
CountX is not a named column. CountX不是命名列。
This may not be the most optimal way, but wrapping the entire query might work. 这可能不是最佳方法,但是包装整个查询可能有效。
SELECT CountX, Acct_No
FROM
(
select (select count(*) from dbo.client as cl2
where cl2.acct_no like (cl1.acct_no + '-%')) as countx, acct_no
from dbo.client as cli
) As InnerQuery
where countx = 0
Edit 编辑
Looking at this, it may be better Accomplished using a Join, instead of that nested Select. 鉴于此,使用联接而不是嵌套的Select可能更好地实现。
SELECT cl1.acct_no, Count(*)
FROM dbo.client cl1 --the master key numbers
INNER JOIN dbo.client cl2 --the sub-keys
ON cl1.acct_no NOT LIKE '%-%' --No dashes in the MasterKey
AND cl1.acct_no LIKE (cl2.acct_no + '-%')
GROUP BY cl1.acct_no
Try using in
to get what you want 尝试使用
in
获得您想要的东西
select Acct_No from dbo.client where Acct_No not in
(
select acct_no from dbo.client where acct_no like acct_no + '-%'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.