sql >> Databasteknik >  >> RDS >> Sqlserver

SQL-fråga för att ansluta/förena två tabeller

Detta har testats i SQL Server 2008 R2. Jag tror att allt här kommer att fungera under 2005 också. 2005, såvitt jag minns, introducerade bland annat PIVOT och OVER. Om du hittar några problem, låt mig bara veta.

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;



  1. Hur genererar man en dynamisk sekvenstabell i MySQL?

  2. Hur man slår samman två django-modeller (tabeller) till en modell (tabell)

  3. Hur man migrerar från Oracle DB till MariaDB

  4. Konstruera MySQL-fråga (meta_key/meta_value-tabell)