简体   繁体   中英

SQL 2 counts or 2 sums when a date column is selected

I've been trying to figure this out, but can't get it right.

I want to select the ID, table S date, 2 different counts for the number of Type = 1 and Type = 2 where the date in table P is >= the max date from table S where note = J, and a date difference between the max table P date and the table S date.

Example table data:

Table S     
Date          ID    Note
2/26/2014   688606  J
2/14/2014   688606  J


Table P 
Date          ID    Type
7/10/2015   688606  1
7/9/2015    688606  1
7/8/2015    688606  1
7/7/2015    688606  2
1/2/2010    688606  1
1/1/2010    688606  2

Ideal result set:

S.Date      S.ID    P.MaxDate   P.T1Count   P.T2Count   P.DateDiff
2/26/2014   688606  7/10/2015       3            1         499

I've tried SUMs, but then I can't figure out how to incorporate the dates since SUM requires a group by and the dates are all unique.

I tried counts with a partition by the ID, but that makes the count include all data in table P rather than just those with dates >= table S.

Any help is really appreciated.

Thanks,

Here's my go at it with only 1 count:

SELECT 
S.ID,
S.DATE as SDATE,
P.DATE as PDATE,
P.TYPE,
COUNT(P.DATE) OVER (PARTITION BY P.ID) as NBR_T1,
(P.DATE - S.DATE)as NBR_DATES
FROM
P
JOIN 
(
SELECT
DISTINCT(S.ID),
S.DATE,
S.NOTE 
FROM 
S
WHERE 
S.DATE = (SELECT MAX(SS.DATE)
FROM SS
WHERE SS.ID = S.ID
AND SS.NOTE = 'J')
AND S.ID = '688606'
) S ON P.ID = S.ID
WHERE
P.TYPE = '1' 
AND P.ID = '688606'
AND P.DATE >= S.DATE

ORDER BY 
P.DATE DESC

If you really only have 2 types then this solution will work. If you have N types and you therefor want N columns that you'd need to use a PivotTable .

Hopefully this helps.

    USE SomeDB;

    CREATE TABLE S (dt DATETIME NOT NULL, sTableid INT NOT NULL);

    INSERT INTO S VALUES ('2/26/2014', 688606), ('2/14/2014', 688606);

    CREATE TABLE P (dt DATETIME NOT NULL, pTableid INT NOT NULL, typeID INT NOT NULL);

    INSERT INTO P VALUES 
    ('7/10/2015', 688606, 1),
    ('7/9/2015', 688606, 1),
    ('7/8/2015', 688606,  1),
    ('7/7/2015', 688606, 2),
    ('1/2/2010', 688606, 1),
    ('1/1/2010', 688606,  2);

    WITH tmp AS (
    SELECT pTableid, p.typeID, MAX(dt) maxDate, COUNT(1) cnt
    FROM dbo.P
    GROUP BY pTableid, p.typeID
    )
SELECT s.dt, 
    s.sTableid, 
    (SELECT MAX(maxDate) FROM tmp WHERE tmp.pTableid = s.sTableid) maxDateOfAnyType,
    (SELECT cnt FROM tmp WHERE tmp.pTableid = s.sTableid AND tmp.typeID = 1) t1Count,
    (SELECT cnt FROM tmp WHERE tmp.pTableid = s.sTableid AND tmp.typeID = 2) t2Count,
    DATEDIFF(DAY, s.dt, (SELECT MAX(maxDate) FROM tmp WHERE tmp.pTableid = s.sTableid)) daysBetween
FROM dbo.S s    

    DROP TABLE S;
    DROP TABLE P;

This is probably easiest if you aggregate the data in S first—I like CTEs for this—and then apply the necessary aggregation to the corresponding data in P . Like so:

-- Sample data.
declare @s table ([Date] date, [ID] bigint, [Note] char(1));
insert @s values
    ('2014-02-26', 688606, 'J'),
    ('2014-02-14', 688606, 'J');

declare @p table ([Date] date, [ID] bigint, [Type] int);
insert @p values
    ('2015-07-10', 688606, 1),
    ('2015-07-09', 688606, 1),
    ('2015-07-08', 688606, 1),
    ('2015-07-07', 688606, 2),
    ('2010-01-02', 688606, 1),
    ('2010-01-01', 688606, 2);

-- Step 1: Aggregate and filter the records you want in @s.
with [GroupS] as
(
    select
        [S].[ID],
        [Date] = max([S].[Date])
    from
        @s [S]
    where
        [S].[Note] = 'J'
    group by
        [S].[ID]
)

-- Step 2: Aggregate the corresponding records in @p.
select
    [S.Date] = [GroupS].[Date],
    [S.ID] = [GroupS].[ID],
    [P.MaxDate] = max([P].[Date]),
    [P.T1Count] = sum(case [P].[Type] when 1 then 1 else 0 end),
    [P.T2Count] = sum(case [P].[Type] when 2 then 1 else 0 end),
    [P.DateDiff] = datediff(day, [GroupS].[Date], max([P].[Date]))
from
    [GroupS]
    inner join @p [P] on [GroupS].[ID] = [P].[ID]
where
    [GroupS].[Date] <= [P].[Date]
group by
    [GroupS].[Date],
    [GroupS].[ID];

Another way of doing it... I assume you have table S and P already created and using SQL Server 2012+ .

Declare @MDate datetime
SELECT @MDate = MAX(SS.DATE) FROM S SS WHERE SS.NOTE = 'J'

Select S.Date, S.ID, Max(P.Date) as 'MaxDate', 
COUNT(IIF(convert(int,P.Type)=1, 1, NULL)) AS T1Count,
COUNT(IIF(convert(int,P.Type)=2, 1, NULL)) AS T2Count,
datediff(day, S.Date, Max(P.Date)) as 'DateDiff' from P 
inner join S on P.ID = S.ID and S.Date >= @MDate
and P.Date >= @MDate
group by S.Date, S.ID

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