0

请想象以下表格:

发票

|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 报告中进行分组。

感谢您的热心帮助。

4

1 回答 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]
于 2012-12-10T07:18:59.430 回答