2015-05-07 30 views
0

我目前在SQL 2012可视化管理工作室工作。我有两张桌子。 Table1有三列(ItemNumber为varchar,Quantity为int,TimeOrdered为datetime)。表2有2列(ItemNumber作为varchar,Price作为float)。请注意这些项目编号不一样,表1中的部件号在编号后面有一个字母,而表2项目编号没有。例如,在表1中,项目编号看起来像这样999999999-E,另一个表格将只是999999999-。因此,我必须使用选择左边的10位数来获得零件号。选择左边10个数字,左边加入一个价格从第二个表格,然后求和,SQL

我需要根据订购的时间从表1中提取一个物品编号列表,然后将该列表与表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 

在这里,我收到了一条错误的集合列,但我不知道这是去这个问题,开始用正确的方式。

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

我明白了。对不起,花了这么长的时间才回到你们身边,我整天呆在一次会议中,

回答

1

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

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 
+0

给我一会儿,而我试试这个。 – Cheddar

+0

我得到这个工作,我有总的专栏。现在我怎么能不用Excel电子表格和手动添加它们来总和总计列。 – Cheddar

+0

SELECT Sum(grandtotal)from( - 在这里写上述查询 )a –

0

SQL服务器要求你明确指出group by你没有聚合的列。所以你需要添加group by tbl.PartNumber, tbl.quantity, table2.price。当然,这是大概会使tbl.quantity * table2.price种无用。你究竟在做什么? :)

0

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 
+0

给我片刻,我试试这个 – Cheddar

+0

我所有的列选择table1的T1以上的不能绑定。有任何想法吗? – Cheddar

+0

你能发布代码吗?我测试了它,并为我工作 – SQLChao

0

Here是一个提供一些样本数据,应该给你你想要的小提琴。您需要在群组中包含任何非聚合列。

你的代码最终如下:

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 
相关问题