Select 留下 10 个数字,从第二个 table 开始加入一个价格,然后求和,SQL

Select left 10 numbers, left join for a price from second table, and then sum, SQL

我目前在 sql 2012 visual management studio 工作。我有两个 table。 Table1 具有三列(ItemNumber 为 varchar,Quantity 为 int,TimeOrdered 为 datetime)。 Table2 有 2 列(ItemNumber 为 varchar,Price 为 float)。请注意,这些货品编号不同,table 1 上的零件号在编号后有一个字母,而 table 2 货品编号则没有。例如,在 table 1 上,项目编号将类似于 999999999-E,而另一个 table 将仅为 999999999-。因此,我必须使用 select 左 10 位数字来获取零件号。

我需要根据订购时间从 table 1 中提取项目编号列表,然后将该列表与 table 2 进行交叉比较,并将价格乘以数量乘以总计.到目前为止,这是我的代码:

SELECT sum(tbl.quantity * table2.price) as grandtotal,
       tbl.PartNumber,
       tbl.quanity,
       table2.price
FROM
   (SELECT left(itemnumber, 10) as itemnumber, quantity 
    FROM table1 
    WHERE TimeOrdered between 
                            ('2014-05-05 00:00:00.000')
                      AND 
                            ('2015-05-05 00:00:00.000')) as tbl 
Left table2 on
tbl.partnumber =tbl2.itemnumber

我在此处收到有关聚合列的错误,但我不确定这是开始此操作的正确方法。

------------更新----------------

我成功了。很抱歉花了这么长时间才回复你们,我整天都在开会,

SQL 服务器要求您明确 group by 您不作为聚合依据的列。所以你需要加上group by tbl.PartNumber, tbl.quantity, table2.price。当然,这 可能 会使 tbl.quantity * table2.price 变得毫无用处。你到底想做什么? :)

SQL Fiddle Example

 SELECT SUM(t1.quantity * t2.price) AS 'GrandTotal'
    ,SUM(t1.quantity) AS 'Quantity'
    ,t1.itemnumber
    ,t2.price
 FROM Table1 t1
 JOIN Table2 t2 ON LEFT(t1.itemnumber, 10) = t2.itemnumber 
 WHERE t1.Timeordered BETWEEN '2014-05-05 00:00:00.000' AND '2015-05-05 00:00:00.000'
 GROUP BY t1.itemnumber, t2.price

这个怎么样。这种情况只是为了避免 div 零错误。

SELECT sum( Isnull(tbl.quantity,0) * Isnull(table2.price,0) ) as grandtotal,
tbl.PartNumber,
Sum(tbl.quanity),
case when Isnull(Sum(tbl.quanity),0) = 0 then null else 
      sum(Isnull(tbl.quantity,0) * Isnull(table2.price,0) ) / Sum(tbl.quanity) end 
as Price
FROM
(SELECT left(itemnumber, 10) as itemnumber, quantity FROM table1 WHERE TimeOrdered between 
('2014-05-05 00:00:00.000')
AND ('2015-05-05 00:00:00.000')) as tbl 
Left outer join table2 on
tbl.partnumber =tbl2.itemnumber
group by tbl.PartNumber

Here 是一个 fiddle,其中包含一些示例数据,应该可以满足您的需求。您需要在分组依据中包含任何非聚合列。

您的代码最终如下所示:

SELECT left(table1.ItemNumber, 10) as PartNumber,
       table2.price,
       sum(table1.quantity) as totalquantity,
       sum(table1.quantity * table2.price) as grandtotal
FROM table1
INNER JOIN table2 ON left(table1.ItemNumber, 10) = table2.ItemNumber
WHERE t1.Timerordered BETWEEN '2014-05-05 00:00:00.000' AND '2015-05-05 00:00:00.000'
GROUP BY table1.ItemNumber, table2.price