2016-08-25 71 views
0

我想选择查询返回的行数的计数。查询是在子查询中选择计数的SQL Server错误

Select 
    a.itm_cd, max(b.doc_num) ,max(c.text) 
from 
    ist b, itm_trn a, ist_cmnt c 
where 
    a.ist_seq_num = b.ist_seq_num 
    and a.ist_seq_num = c.ist_seq_num 
    and a.ist_wr_dt = b.ist_wr_dt 
    and a.new_loc_cd like 'BOX115' 
    and a.ITT_CD = 'XFR' and a.create_dt >'21-AUG-16' 
group by 
    a.itm_cd; 

对于这个特定的查询我返回3行,我需要编写一个查询,返回多少行返回。

我曾尝试这样的:

Select 
    count(*) 
from 
    (Select 
     a.itm_cd, max(b.doc_num), max(c.text) 
    from 
     ist b,itm_trn a, ist_cmnt c 
    where 
     a.ist_seq_num = b.ist_seq_num 
     and a.ist_seq_num = c.ist_seq_num 
     and a.ist_wr_dt = b.ist_wr_dt 
     and a.new_loc_cd like 'BOX115' 
     and a.ITT_CD = 'XFR' 
     and a.create_dt > '21-AUG-16' 
    group by 
     a.itm_cd); 

这将导致一个语法错误

消息102,15级,状态1线1
附近有语法错误 ')'。

我不知道我在做什么错误,我有一个类似的SQL语句,它在Oracle中以这种方式工作,但没有找到我在SQL Server中搞乱的地方。

UPDATE:

按照第一个建议,我收到我的尝试:返回

Select 
    count(*) 
from 
    (Select 
     a.itm_cd, max(b.doc_num), max(c.text) 
    from 
     ist b, itm_trn a, ist_cmnt c 
    where 
     a.ist_seq_num = b.ist_seq_num 
     and a.ist_seq_num = c.ist_seq_num 
     and a.ist_wr_dt = b.ist_wr_dt 
     and a.new_loc_cd like 'BOX115' 
     and a.ITT_CD = 'XFR' 
     and a.create_dt > '21-AUG-16' 
    group by 
     a.itm_cd) as T 

误差范围为

消息8155,级别16,状态2,12号线
'T'的第2列未指定任何列。

消息8155,级别16,状态2,行12
'T'的列3没有指定列。

+1

你需要一个别名添加到您的派生表:通过a.itm_cd'组)为T;' – Lamak

+0

尝试,错误我得到的是没有柱子的“T”的2栏中指明,并没有列是为'T'的第3列指定 – Danimal

+1

您甚至不需要这些列来计算计数:'select count(*)from(通过a.itm_cd选择a.itm_cd。..........组)作为T;' – Lamak

回答

0

根据错误消息,您应该为聚合列添加别名。这样试试,

SELECT count(*) 
FROM (
    SELECT a.itm_cd 
     ,max(b.doc_num) AS MaxDoc_num 
     ,max(c.TEXT) AS MaxText 
    FROM ist b 
     ,itm_trn a 
     ,ist_cmnt c 
    WHERE a.ist_seq_num = b.ist_seq_num 
     AND a.ist_seq_num = c.ist_seq_num 
     AND a.ist_wr_dt = b.ist_wr_dt 
     AND a.new_loc_cd LIKE 'BOX115' 
     AND a.ITT_CD = 'XFR' 
     AND a.create_dt > '21-AUG-16' 
    GROUP BY a.itm_cd 
    ) T 

您可以使用此查询轻松找到计数。

SELECT count(DISTINCT a.itm_cd) 
FROM ist b 
    ,itm_trn a 
    ,ist_cmnt c 
WHERE a.ist_seq_num = b.ist_seq_num 
    AND a.ist_seq_num = c.ist_seq_num 
    AND a.ist_wr_dt = b.ist_wr_dt 
    AND a.new_loc_cd LIKE 'BOX115' 
    AND a.ITT_CD = 'XFR' 
    AND a.create_dt > '21-AUG-16'