Home Forums SQL Server 2008 T-SQL (SS2K8) Get multiple rows of data based on one condition and grouping RE: Get multiple rows of data based on one condition and grouping

  • Is customer ID Supposed to be the same across all customers?

    CREATE TABLE #CustomerPurchase(

    [PurchaseDate] [datetime] NOT NULL,

    [CustomerID] [int] NOT NULL,

    [CustomerName] [varchar](25) NULL,

    [PurchaseDetails][varchar](500)NULL

    ) ON [PRIMARY]

    GO

    --Insert some sample data into the sample table

    GO

    INSERT INTO #CustomerPurchase ( PurchaseDate, CustomerID, CustomerName, PurchaseDetails)

    SELECT '2012-06-01 00:00:00.000',1001,'Wilson Menthis','Purchased Item 6AB2'

    UNION ALL

    SELECT '2012-06-01 00:00:00.000',1001,'Wilson Menthis','Loyalty Customers'

    UNION ALL

    SELECT '2012-06-01 00:00:00.000',1001,'Wilson Menthis','20%DiscountReceived on Office Furniture'

    UNION ALL

    SELECT '2012-06-01 00:00:00.000',1001,'John Gray','Purchased $250 worth of Miscellaneous Products'

    UNION ALL

    SELECT '2012-06-01 00:00:00.000',1001,'Kevin Chang','Loyalty Customers'

    UNION ALL

    SELECT '2012-06-01 00:00:00.000',1001,'Kevin Chang','Returned OfficeDesk due to defect on the surface'

    GO

    --Select some data from the table for the particular day

    SELECT *

    FROM #CustomerPurchase cp

    INNER JOIN (SELECT *

    FROM #CustomerPurchase

    WHERE PurchaseDate = '2012-06-01 00:00:00.000'

    AND PurchaseDetails = 'Loyalty Customers') AS lc

    ON cp.CustomerName = lc.CustomerName

    -- Remove this if you don't care what date the customers purchases were for, or Add < if you only want purchases before this date

    AND cp.PurchaseDate = lc.PurchaseDate