2013-04-28 69 views
1

我使用SQL Server 2008的修改結果表

這是結果表

ItemCode ItemName   Branch  Total Weight 
------------------------------------------------------ 
FBV0001 SML WATER ARWA  Bayan   144.00 
FDR0014 RED LENTIL   Al Balad  3000.00 
FDR0014 RED LENTIL   Solidere 13500.00 
FDR0017 EGYPTIAN RICE  Solidere 75500.00 

如何修改結果如下

ItemCode ItemName   Bayan  Al Balad Solidere 
-------------------------------------------------------------- 
FBV0001 SML WATER ARWA  144.00  0   0 
FDR0014 RED LENTIL   0  3000.00   0 
FDR0014 RED LENTIL   0   0  13500.00 
FDR0017 EGYPTIAN RICE   0   0  75500.00 

我已經試過很多查詢,但它不管用。請給出一個想法如何獲得這個。

+2

你可能想[PIVOT] (http://msdn.microsoft.com/en-us/library/ms177410(SQL.105).aspx)。這組分支是否固定? – Rup 2013-04-28 11:46:08

+0

是的,分支機構是固定的 – 2013-04-28 11:53:09

回答

1

使用Pivot表運算符。事情是這樣的:

WITH CTE 
AS 
(
    SELECT *, ROW_NUMBER() OVER(ORDER BY ItemCode) AS RN 
    FROM tablename 
) 
SELECT 
    ItemCode, 
    ItemName, 
    [Bayan], [Al Balad], [Solidere] 
fROM CTE AS t 
PIVOT 
(
    MAX(TotalWeight) 
    FOR Branch IN ([Bayan], [Al Balad], [Solidere]) 
) AS p; 

需要注意的是:我用ROW_NUMBER()產生通過它來使用一組唯一的ID。如果您沒有使用ROW_NUMBER(),你會從兩個只得到一個行:

FDR0014  RED LENTIL 
FDR0014  RED LENTIL 

看到它在這裏的行動:

這會給你:

| ITEMCODE |  ITEMNAME | BAYAN | AL BALAD | SOLIDERE | 
------------------------------------------------------------ 
| FBV0001 | SML WATER ARWA | 144 | (null) | (null) | 
| FDR0014 |  RED LENTIL | (null) |  3000 | (null) | 
| FDR0014 |  RED LENTIL | (null) | (null) | 13500 | 
| FDR0017 | EGYPTIAN RICE | (null) | (null) | 75500 | 
+0

非常感謝您的即時回覆。它的工作就像一個魅力。非常感謝。高超。我會增加我的數據透視表的知識 – 2013-04-28 12:09:27

+0

是的,我檢查了。非常好的指導。我真的很感激mahmoud gamal – 2013-04-28 12:18:55

+0

接受答案 – 2013-04-28 12:41:02

0

嘗試this..here SQL FIDDLE DEMO

Select [itemcode],[itemname], 
(Case when [branch]='Bayan' then [totalweight] else 0 end) as Bayan, 
(Case when [branch]='AL BALAD' then [totalweight] else 0 end) as AL_BALAD, 
(Case when [branch]='SOLIDERE' then [totalweight] else 0 end) as SOLIDERE 
from Tablename 

輸出是這樣的..

ItemCode   ItemName     Bayan  Al Balad   Solidere 
FBV0001  SML WATER ARWA    144   0    0 
FDR0014  RED LENTIL     0  3000    0 
FDR0014  RED LENTIL     0   0    13500 
FDR0017  EGYPTIAN RICE     0   0    75500 
+0

嗨艾米特singh這也是工作正常。非常感謝您的支持 – 2013-04-28 12:45:35

+0

歡迎.... @ priyaamali – 2013-04-28 12:51:58