2010-07-19 78 views
-1

這裏是非常詳細的概率:我想有這個場在我的ReportViewerSQL交叉問題

 
customer name location1   location2    location3 
cust1   capitol, cebu city gen. maxilom, cebu city guadalupe, cebu city 
cust2   paknaan, mandaue basak, mandaue   lapu-lapu city 

請幫助這個日期只屬於1個表

 
custcode address 
cust1  capitol, cebu city 
cust1  gen. maxilom, cebu city 
cust1  guadalupe, cebu city 
cust2  paknaan, mandaue city 
cust2  basak, mandaue city 
cust3  lapu-lapu city 

在我的報告..

+0

你如何區分location1和location2等等你有一個值爲1,2,3的列嗎?你使用的是什麼RDBMS? – 2010-07-19 10:18:56

+0

我正在使用mssql先生。不,先生,我沒有這些列,但我有一個ID字段。我想嘗試交叉表,但我不知道如何獲取位置列。 – pilots 2010-07-19 23:43:29

+0

mssql - Microsoft SQL Server?如果是的話,只要你在2005年或以後,我的第二個版本就可以爲你工作。 – 2010-07-20 19:26:50

回答

0

如果你有一個位置字段,你沒有告訴我們可以區分每列中的含義

SELECT 
custcode, 
MAX(CASE WHEN location = 1 THEN address END) AS location1, 
MAX(CASE WHEN location = 2 THEN address END) AS location2, 
MAX(CASE WHEN location = 3 THEN address END) AS location3 
FROM X 
GROUP BY custcode 

如果你依靠行排序SQL Server特定的答案。

這假定您有一個ID字段,可以從中計算「第一個」行的順序。

with X as 
(
SELECT 1 AS ID, 'cust1' AS custcode, 'capitol, cebu city' AS address 
UNION ALL 
SELECT 2 AS ID, 'cust1' AS custcode, 'gen. maxilom, cebu city' AS address 
UNION ALL 
SELECT 3 AS ID, 'cust1' AS custcode, 'guadalupe, cebu city' AS address 
UNION ALL 
SELECT 4 AS ID, 'cust2' AS custcode, 'paknaan, mandaue city' AS address 
UNION ALL 
SELECT 5 AS ID, 'cust2' AS custcode, 'basak, mandaue city' AS address 
UNION ALL 
SELECT 6 AS ID, 'cust2' AS custcode, 'lapu-lapu city' 
) 
, Y AS 
(
SELECT ROW_NUMBER() OVER (PARTITION BY custcode ORDER BY ID) AS RN, 
     custcode, 
     address 
FROM X 
) 

SELECT custcode, [1] AS location1 , [2] AS location2,[3] AS location3 FROM Y 
PIVOT 
( 
Max(address) 
FOR RN IN ([1], [2],[3]) 
) AS PivotTable;