2016-08-25 63 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'