我正在寻找一些建议来构建查询以加入表A&表B以表C的形式获取输出。看起来我需要能够将两个表联合起来并构建一个交叉表查询。下面显示的数据仅仅是示例,因为两个表中的日期每个月都会发生变化。注意:两个表中的日期不会重叠。例如,在表B下面,FutureDates永远不会是6月或7月。反之亦然
Table A
Product Location HistoryDate HistorySales ... more columns
A X June 100
A X July 200
Table B
Product Location FutureDate FutureSales ... more columns
A X August 150
A X Sept 50
Table C
Product Location June July August September ... other columns from A & B
A X 100 200 150 50
感谢您的帮助。
答案 0 :(得分:2)
这已在SQL Server 2008 R2中测试过。我相信这里的一切都将在2005年发挥作用。 2005年,据我记得,推出了PIVOT和OVER等等。如果您发现任何问题,请告诉我。
DECLARE @Products TABLE
(
ID INT IDENTITY(1, 1)
, Name VARCHAR(30)
);
INSERT INTO @Products
VALUES ('Dummies Guide to Querying'), ('SQL Design Patterns');
DECLARE @OldProducts TABLE
(
ID INT IDENTITY(1, 1)
, ProductID INT
, Location CHAR(2)
, HistoryDate DATE
, Sales INT
);
INSERT INTO @OldProducts
VALUES (1, 'CO', '20100601', 100)
, (1, 'CO', '20100701', 200)
, (1, 'CA', '20100526', 150)
, (2, 'CA', '20100601', 175);
DECLARE @NewProducts TABLE
(
ID INT IDENTITY(1, 1)
, ProductID INT
, Location CHAR(2)
, FutureDate DATE
, PredictedSales INT
);
INSERT INTO @NewProducts
VALUES (1, 'CO', '20110401', 200)
, (1, 'CO', '20110601', 250)
, (1, 'CA', '20110401', 150)
, (2, 'CA', '20110301', 180)
, (3, 'WA', '20110301', 100);
WITH AllProduts AS
(
SELECT
Products.Name
, OldProducts.Location
, DATENAME(MONTH, OldProducts.HistoryDate) AS MonthValue
, OldProducts.Sales
FROM @OldProducts AS OldProducts
INNER JOIN @Products AS Products
ON Products.ID = OldProducts.ProductID
UNION ALL
SELECT
Products.Name
, NewProducts.Location
, DATENAME(MONTH, NewProducts.FutureDate) AS MonthValue
, NewProducts.PredictedSales AS Sales
FROM @NewProducts AS NewProducts
INNER JOIN @Products AS Products
ON Products.ID = NewProducts.ProductID
)
SELECT
Name
, Location
, [January]
, [Febuary]
, [March]
, [April]
, [May]
, [June]
, [July]
, [August]
, [September]
, [October]
, [November]
, [December]
FROM AllProduts
PIVOT
(
SUM(Sales)
FOR MonthValue
IN
(
[January]
, [Febuary]
, [March]
, [April]
, [May]
, [June]
, [July]
, [August]
, [September]
, [October]
, [November]
, [December]
)
) PivotedTable
ORDER BY Name, Location;