我正在使用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
我已经尝试了很多查询,但它不起作用。请说明如何获得这个。
答案 0 :(得分: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 |
答案 1 :(得分:0)
试试这个...... 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