记录计数(嵌套??)

时间:2017-06-07 10:39:48

标签: sql sql-server sql-server-2014

我有一个SQL select语句,除了我需要嵌入一个计数函数(第7行和第8行)之外,它可以正常工作。

select '1' = DYN_PORDERS.ID, '2' = DYN_PORDERS.SupplierID,'3' = 
DYN_PORDERS.Revision2,  
'4' = DYN_PORDERS.ItemID,  '5' = DYN_PORDERS.OrderNumber, '12' = '',
'6' = SYS_SUPPLIERS.SCompany, '7' = SYS_SUPPLIERS.SCode, '8' = 
SYS_SUPPLIERS.SCIPEMail, '9' = SYS_SUPPLIERS.SCIPContact, 
'10' = SYS_SUPPLIERS.SPDRemitType, '11' = SYS_SUPPLIERS.SCIPFax,
(SELECT count(DYN_PORDERS.OrderNumber) FROM DYN_PORDERS where OrderNumber = 
'5') AS column3
from DYN_PORDERS 
inner join  SYS_SUPPLIERS 
on SYS_SUPPLIERS.ID = DYN_PORDERS.SupplierID 
where DYN_PORDERS.OrderStatus1 = 1 and DYN_PORDERS.ItemID = 1
order by DYN_PORDERS.OrderNumber asc, DYN_PORDERS.itemid asc

嵌套的select count语句返回0,但表中有四条记录。

我试图从嵌入式语句中的第一个select语句引用变量​​或列名“5”,但它返回0.

非常感谢任何帮助。 麦克

2 个答案:

答案 0 :(得分:0)

如果要访问子查询中的ordernumber,请使用此名称。使用表别名从内部表中告诉外部表。

select 
  p.id as "1", 
  p.supplierid as "2",
  p.revision2 as "3",  
  p.itemid as "4",  
  p.ordernumber as "5", 
  '' as "12",
  s.scompany as "6", 
  s.scode as "7",
  s.scipemail as "8", 
  s.scipcontact as "9", 
  s.spdremittype as "10", 
  s.scipfax as "11",
  (select count(*) from dyn_porders p2 where p2.ordernumber = p.ordernumber) as column3
from dyn_porders p
inner join sys_suppliers s on s.id = p.supplierid 
where p.orderstatus1 = 1 
  and p.itemid = 1
order by p.ordernumber asc, p.itemid asc;

请注意,单引号用于字符串文字,双引号用于名称。

答案 1 :(得分:0)

我想你想要这样的东西:

select p.ID as col_1, p.SupplierID as col_2, p.Revision2 as col_3,  
       p.ItemID as col_4, p.OrderNumber as col_5, '' as col_12,
       s.SCompany as col_6, s.SCode as col_7, s.SCIPEMail as col_8,
       s.SCIPContact as col_9, s.SPDRemitType as col_10, s.SCIPFax as col_11,
       (select count(*)
        from DYN_PORDERS p2
        WHERE p2.OrderNumber = 5
       ) as column3
from DYN_PORDERS  p inner join
     SYS_SUPPLIERS s 
     on s.ID = p.SupplierID 
where p.OrderStatus1 = 1 and p.ItemID = 1
order by p.OrderNumber asc, p.itemid asc;

注意:

  • 我强烈建议你将列命名为数字。这只是令人困惑,需要转义字符(可能因数据库而异)。
  • 使用表别名缩写的表别名。查询更容易编写和阅读。
  • 不要在数字常量周围使用单引号。