[英]Sql query to join/union two tables
I am looking for some suggestions to build a query to join table A & table B to get the output as table C. It looks like I need to be able to union the two tables and build a cross tab query. 我正在寻找一些建议,以建立一个查询来联接表A和表B,以将输出作为表C。看起来我需要能够将两个表结合起来并建立一个交叉表查询。 The data shown below are just examples as the dates in the two tables would be changing every month. 下面显示的数据仅是示例,因为两个表中的日期每月都会更改。 Note: the dates in the two tables will not overlap. 注意:两个表格中的日期不会重叠。 For example, below Table B will never have FutureDates as June or July. 例如,在表B下面将永远不会有FutureDate作为六月或七月。 and vice-versa 反之亦然
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
Thanks for any help. 谢谢你的帮助。
This has been tested in SQL Server 2008 R2. 这已在SQL Server 2008 R2中进行了测试。 I believe everything here will work in 2005 as well. 我相信这里的所有内容都将在2005年正常运行。 2005, as far as I remember, introduced PIVOT and OVER among other things. 据我所知,2005年推出了PIVOT和OVER等产品。 If you find any problems just let me know. 如果您发现任何问题,请告诉我。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.