2015-05-07 27 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 
相關問題