We help IT Professionals succeed at work.

Obtaining Transactions Greater Than 90 Days T-SQL

Trent Adams
Trent Adams asked
on
74 Views
Last Modified: 2018-11-21
I need to get expenses that are 90 days past due and have not been approved or paid. I can get the first part, however, when I attempt to perform a case when...the aggregation seems to get destroyed.

SELECT ex.ExpenseTypeID, 
       COUNT(*) AS ExpenseType, 
       ext.Description,
       CASE
           WHEN DATEDIFF(day, ExpenseDate, GETDATE()) >= 90
           THEN 90
           WHEN(DATEDIFF(day, ExpenseDate, GETDATE()) >= 60
                AND DATEDIFF(day, ExpenseDate, GETDATE()) < 90)
           THEN 60
           WHEN(DATEDIFF(day, ExpenseDate, GETDATE()) >= 30
                AND DATEDIFF(day, ExpenseDate, GETDATE()) < 60)
           THEN 30
       END
FROM tbl_Expenses ex
     INNER JOIN tbl_ExpenseType ext ON ex.ExpenseTypeID = ext.ExpenseTypeID
WHERE EmployeeID = 88
      AND ExpenseDate <= DATEADD(day, -90, GETDATE())
      AND (Approved = 0
           OR Paid = 0
           AND IsVoided = 0)
GROUP BY ex.ExpenseTypeID, 
         ext.Description,
		 ex.ExpenseDate;

Open in new window

Comment
Watch Question

Scott PletcherSenior DBA
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
All expenses must be at least 90 days old, so the current CASE statement would only ever return "90" anyway.

I'd also add extra parentheses to the WHERE condition just to be very clear about the conditions:

AND ((Approved = 0
           OR Paid = 0)
           AND IsVoided = 0)
PortletPaulEE Topic Advisor
CERTIFIED EXPERT
Most Valuable Expert 2014
Awarded 2013

Commented:
Not sure what you are attempting to achieve, but in addition to the avove the group by clause needs to use the same case expression
SELECT
    ex.ExpenseTypeID
  , ext.Description
  , CASE
        WHEN DATEDIFF( DAY, ExpenseDate, GETDATE() ) >= 90 THEN 90
        WHEN (DATEDIFF( DAY, ExpenseDate, GETDATE() ) >= 60 AND
            DATEDIFF( DAY, ExpenseDate, GETDATE() ) < 90) THEN 60
        WHEN (DATEDIFF( DAY, ExpenseDate, GETDATE() ) >= 30 AND
            DATEDIFF( DAY, ExpenseDate, GETDATE() ) < 60) THEN 30
    END AS Age
  , COUNT( * ) AS ExpenseType
FROM tbl_Expenses ex
INNER JOIN tbl_ExpenseType ext ON ex.ExpenseTypeID = ext.ExpenseTypeID
WHERE EmployeeID = 88
AND ExpenseDate <= DATEADD( DAY, -90, GETDATE() )
AND ((Approved = 0 OR Paid = 0)
AND IsVoided = 0)
GROUP BY
    ex.ExpenseTypeID
  , ext.Description
  , CASE
        WHEN DATEDIFF( DAY, ExpenseDate, GETDATE() ) >= 90 THEN 90
        WHEN (DATEDIFF( DAY, ExpenseDate, GETDATE() ) >= 60 AND
            DATEDIFF( DAY, ExpenseDate, GETDATE() ) < 90) THEN 60
        WHEN (DATEDIFF( DAY, ExpenseDate, GETDATE() ) >= 30 AND
            DATEDIFF( DAY, ExpenseDate, GETDATE() ) < 60) THEN 30
    END

Open in new window

Trent AdamsDevOps Lead

Author

Commented:
The goal here is to return results which will be used for analytics on a dashboard.
I’m trying to get expenses for a user based on the employeeID and expense date. Criteria is expenses which are not approved with the last 90 days and expenses that haven’t been paid or voided.
These will be displayed with an alias column which show if they are 30,60 or 90 days plus.
This will be used to help users see if they have any expenses which haven’t been approved and paid within a 99 day period.
PortletPaulEE Topic Advisor
CERTIFIED EXPERT
Most Valuable Expert 2014
Awarded 2013

Commented:
Trent,
the very best way to define your required output is to use a mock-up.
Words are notoriously bad at describing requirements, for example I don't really know what you mean by:
"These will be displayed with an alias column"

Is that 3 columns like this?
+------------+---------------+-----+-----+-----+
| employeeID |  expense date |  30 |  60 |  90 |
+------------+---------------+-----+-----+-----+

+------------+---------------+--------+
| employeeID |  expense date |  alias |
+------------+---------------+--------+
|            |               |     30 |
|            |               |     60 |
|            |               |     90 |
+------------+---------------+--------+

Open in new window

or the second of those?

Is expense description required in the output?

Experience shows that if you provide sample data and expected result you will get an accurate answer in the minimum time.
Trent AdamsDevOps Lead

Author

Commented:
My apologies. The second is what I’m looking for. The description will be used as an X axis label. So, total the expenses which are 30, 60 and 90 days past due. Then list by expense type with the total days past due (approximation of past due days).

Expected Output
Expense Type  Total   Days Past
Mileage              15       30
Activities             7        60
Tolls                    10       90
EE Topic Advisor
CERTIFIED EXPERT
Most Valuable Expert 2014
Awarded 2013
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
Trent AdamsDevOps Lead

Author

Commented:
Thanks. So there were a couple things I needed to change, otherwise close but no cigar (I should’ve went through my syntax from the bottom up). I greatly appreciate all the help and advice.
PortletPaulEE Topic Advisor
CERTIFIED EXPERT
Most Valuable Expert 2014
Awarded 2013

Commented:
:)

This is what i commonly do when forming a group by query, I COPY the select list under the group by
Then, remove any aliasing

(nb. this is one of the reasons why I list all non-aggregating columns before any aggregations in the select list)

step1: copy

select
      non_aggregating1 as x
    , non_aggregating2 as y
    , case when ... end as z
    , max(x)
    , count(*)
from ...
where ...
group by
      non_aggregating1 as x
    , non_aggregating2 as y
    , case when ... end as z


step2: remove alises

select
      non_aggregating1 as x
    , non_aggregating2 as y
    , case when ... end as z
    , max(x)
    , count(*)
from ...
where ...
group by
      non_aggregating1
    , non_aggregating2
    , case when ... end
Trent AdamsDevOps Lead

Author

Commented:
@PortletPaul
Your break down made a lot of sense. Not to mention it organizes the structure of the query a lot better and makes it more readable. I just keep forgetting that SQL does things in reverse logic (or reversed compared to average human thought).

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions