使用链接表计数函数

时间:2014-01-04 15:27:53

标签: sql-server count

我正在尝试计算2013年每位客户订购的零件数量。
但是,返回的结果似乎按订单编号而非交易者分组。我使用以下select语句;

SELECT orders.traderid, COUNT(orderitems.partid) AS configuredparts
FROM   orders LEFT JOIN orderitems 
ON orders.id = orderitems.orderid AND orders.ordertype = orderitems.ordertype
WHERE        (orderitems.partid LIKE N'P%') AND (YEAR(orders.createddate) = 2013)
GROUP BY orders.traderid, orderitems.partid, orders.ordertype
HAVING        (orders.ordertype = N'SO')
ORDER BY orders.traderid

我的结果的一个例子是

traderid    configured parts
800001           3
800001           3
800001           2
800001           1
A00002           1
A00002           2

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

此答案按表[订单]中的交易者ID给出表[订单商品]中的部件ID总数(计数)。

trader_id        part_id          total_parts
800001           P001             3
800001           P002             2
A00002           P001             1

如果table [order items]有一个qty列,你应该将COUNT(oi.partid)改为SUM(oi.qty)。

SELECT 
  o.traderid as trader_id, 
  oi.partid as part_id,
  COUNT(oi.partid) AS total_parts
FROM   
  orders as o 
LEFT JOIN 
  orderitems as oi
ON 
  o.id = oi.orderid AND 
  o.ordertype = oi.ordertype
WHERE 
  (oi.partid LIKE N'P%') AND 
  (o.createddate >= '20130101') AND
  (o.createddate < '20140101') AND
  (o.ordertype = N'SO')
GROUP BY 
  o.traderid, oi.partid 
ORDER BY 
  o.traderid, oi.partid 

最后但并非最不重要的是,为什么标题有链接表(服务器)?

如果您使用的是链接服务器,则需要使用4部分表示法。

Linked_Server_Name.Database_Name.Schema_Name.Object_Name

答案 1 :(得分:0)

给这个去吧

SELECT orders.traderid, COUNT(orderitems.partid) AS configuredparts
FROM   orders LEFT JOIN orderitems AND orders.ordertype = orderitems.ordertype
ON orders.id = orderitems.orderid 
WHERE (orderitems.partid LIKE N'P%') AND (orders.createddate >= '20130101') 
       AND (orders.createddate < '20140101') AND (orders.ordertype = N'SO')
GROUP BY orders.traderid
ORDER BY orders.traderid