简体   繁体   中英

Group by Calculated Field

I have a dataset with a date, and some values attached to each date. I am aggregating information across accounts, and grouping by account and days active. I want to know how accounts behave on average. I do not care about the DATE, I care about DAYS ACTIVE, so that is where my problem is occurring. I'm trying to create a calculated field (num_days) that is, for each account, the number of days since they first entered the system.

SELECT Acct_ID, L_Type, Num_License, Num_Active, Q_Date - MIN(Q_Date) as Num_days
FROM s.Table
WHERE flag = 'N'
GROUP BY Acct_ID, Num_days

That gives me the error "Invalid Identifier"

I have been reading to just use the calculation again in the group by, so I tried

GROUP BY Acct_ID, Q_Date - MIN(Q_Date)

That gives an error "Group function not allowed here"

How can I go about grouping by number of days? Thanks!

I'm working with SQL server, but I think this one is going to work in Oracle too unless is a very old version.

Basically I think you should split your query in 2 calculating the MIN first and then join back the result with your original table.

WITH CTE as
(   
    SELECT Acct_ID,  MIN(Q_Date) as Q_Date
    from s.Table
    Group by Acct_ID
)
SELECT RT.Acct_ID, RT.L_Type, RT.Num_License, RT.Num_Active, Rt.Q_Date - CTE.Q_Date as Num_days
FROM CTE
    INNER JOIN s.Table RT on CTE.Acct_ID = RT.Acct_ID
WHERE flag = 'N'

Although I don't quite get what you're trying to achieve and I don't think subtracting the MIN QDate you'll have the result you want.

I don't think you want to use aggregate functions (and hence GROUP BY ) at all. Instead, I think you want something like this:

SELECT acct_id, l_type, num_license, num_active
     , q_date - MIN(q_date) OVER ( ) AS num_days
  FROM s.table
 WHERE flag = 'N';

That is, use MIN() as an analytic (window) function instead. Now, if you want to get a count of accounts for each number of active days, you can do something like this:

SELECT TRUNC(num_days), COUNT(*) FROM (
    SELECT acct_id, l_type, num_license, num_active
         , q_date - MIN(q_date) OVER ( ) AS num_days
      FROM s.table
     WHERE flag = 'N'
) GROUP BY TRUNC(num_days);

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