2012-12-10 67 views
0

請想象下表:SQL Server查詢。在查詢中轉換數據?

發票

|Invoice ID  | Invoice Date | 
--------------------------------- 
|1    | 01-11-12  | 
|2    | 01-11-12  | 

服務

|Service ID  | Service Date | Invoice ID | 
------------------------------------------------- 
|1    | 01-11-12  | 1    | 
|2    | 01-11-12  | 1    | 
|3    | 02-11-12  | 1    | 
|4    | 03-11-12  | 1    | 

我想返回一個數據集,像這樣:

|Invoice ID  | Invoice Date | Service ID | Transformed Service Date | Real Service Date | 
--------------------------------------------------------------------------------------------------------  
|1    | 01-11-12  | 1    | 01-11-12     | 01-11-12  | 
|1    | 01-11-12  | 2    | 01-11-12     | 01-11-12  | 
|1    | 01-11-12  | 3    | 01-11-12     | 02-11-12  | 
|1    | 01-11-12  | 4    | 01-11-12     | 03-11-12  | 
|1    | 01-11-12  | 1    | 02-11-12     | 01-11-12  | 
|1    | 01-11-12  | 2    | 02-11-12     | 01-11-12  | 
|1    | 01-11-12  | 3    | 02-11-12     | 02-11-12  | 
|1    | 01-11-12  | 4    | 02-11-12     | 03-11-12  | 
|1    | 01-11-12  | 1    | 03-11-12     | 01-11-12  | 
|1    | 01-11-12  | 2    | 03-11-12     | 01-11-12  | 
|1    | 01-11-12  | 3    | 03-11-12     | 02-11-12  | 
|1    | 01-11-12  | 4    | 03-11-12     | 03-11-12  | 

請注意所有服務在每個服務日期的返回情況。我希望這是可能的。我正在使用此查詢來幫助在SQL Server報告中進行分組。

謝謝你的幫助。

+1

爲什麼不學習查詢? –

回答

3
DECLARE @Invoices TABLE (
[Invoice ID] INT, 
[Invoice Date] DATE) 

DECLARE @Services TABLE (
[Service ID] INT, 
[Service Date] DATE, 
[Invoice ID] INT) 

INSERT INTO @Invoices VALUES 
(1,'2012-11-01'), 
(2,'2012-11-01') 

INSERT INTO @Services VALUES 
(1,'2012-11-01',1), 
(2,'2012-11-01',1), 
(3,'2012-11-02',1), 
(4,'2012-11-03',1) 

;WITH SERVICE_DATE_CTE 
AS 
(
    SELECT DISTINCT [Service Date] FROM @Services 
) 
SELECT 
    I.[Invoice ID], 
    I.[Invoice Date], 
    S.[Service ID], 
    C.[Service Date] AS 'Transformed Service Date', 
    S.[Service Date] AS 'Real Service Date' 
FROM @Invoices I 
INNER JOIN @Services S ON S.[Invoice ID] = I.[Invoice ID] 
CROSS JOIN SERVICE_DATE_CTE C ORDER BY C.[Service Date] 
+0

謝謝你,它指出我在正確的方向。 – Andrew