简体   繁体   中英

Sub-query same column with different criteria

I'm trying to write a sub-query to retrieve values from one of the columns I already selected with the main query, but under different criteria.

在此处输入图像描述

enter image description here

Could you please try this, I think you can use sub queries for Charge and Credit:

SELECT DISTINCT
       [date],[customer],
       Charge = (SELECT Revenue FROM TABLE t2 WHERE t2.customer = t1.customer AND t2.[type] = 'Charge'), 
       Credit = (SELECT Revenue FROM TABLE t2 WHERE t2.customer = t1.customer AND t2.[type] = 'Credit')
FROM TABLE t1

With example data:

CREATE TABLE #temp (thedate date, customer VARCHAR(100), revenue INT, [type] VARCHAR(100))
INSERT INTO #temp values ('2019-01-01','a',10,'charge'),('2019-01-01','a',20,'Credit'),('2019-01-01','b',30,'charge')

SELECT DISTINCT
       [thedate], [customer],
       Charge = (SELECT Revenue FROM #temp t2 WHERE t2.customer = t1.customer AND t2.[type] = 'Charge'), 
       Credit = (SELECT Revenue FROM #temp t2 WHERE t2.customer = t1.customer AND t2.[type] = 'Credit')
FROM #temp t1

I believe this is what you're looking for:

CREATE TABLE #temp (thedate date, customer VARCHAR(100), revenue INT, [type] VARCHAR(100))

INSERT INTO #temp values ('2019-01-01','Acme, Inc.',1000,'Charge')
                        ,('2019-01-01','Amazon',500,'Charge')
                        ,('2019-01-01','Acme, Inc.',100,'Credit')

SELECT [Date]
    , [Customer]
    , [Revenue] as [Charge]
    , [Credit]
FROM #temp t1
OUTER APPLY (
    SELECT sum(revenue) credit
    FROM #temp t2
    WHERE t1.customer = t2.customer
        AND t2.[type] = 'credit'
    ) x
WHERE t1.[type] = 'charge'

Judging solely based on your input data and expected result, the above query should suffice. However, the comments you posted on your question are slightly contradictory with what the image of the expected result shows.

This is the output of my query, based on your input data:

在此处输入图像描述

CREATE TABLE #temp (thedate date, customer VARCHAR(100), revenue INT, [type] VARCHAR(100))

INSERT INTO #temp values ('2019-01-01','Acme, Inc.',1000,'Charge')
                        ,('2019-01-01','Amazon',500,     'CREDIT')
                        ,('2019-01-01','Acme, Inc.',100, 'Credit')


SELECT  THEDATE,
        CUSTOMER,
        MAX(CASE
            WHEN TYPE = 'CREDIT' THEN revenue
        END) AS CREDIT,
        MAX(CASE
            WHEN TYPE = 'CHARGE' THEN REVENUE
        END) AS CHARGE
FROM #TEMP
GROUP BY CUSTOMER, THEDATE

Or you could try PIVOT Function

SELECT  *
FROM #TEMP
PIVOT (MAX(REVENUE)
        FOR 
        [TYPE] IN ([CHARGE],[CREDIT])
        ) AS PIV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM