问题
I would like to create a SELECT query that results in a view that is 30 fields long and 1 record thick. 2 records if we're counting the title.
The specific part of the larger query in question is:
WHERE CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 1
This produces the results desired - records where the days between EVENT_TIMESTAMP and CONTRACT_EFFECTIVE_DATE is 1.
But I'd like this for 30 days. Something like:
WHERE CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 1:30
Is that possible? I could just cut n paste the query 30 times and change the number 1 to the corresponding value. But surely there is a better way?
The results would look something like:
1 day 2 day 3 day 4 day
10 11 8 14
回答1:
That's another PIVOT query, lots of cut&paste again.
Assuming you want to count the number of rows matching each day range:
SELECT
COUNT(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 1 THEN 1 END) AS "1 day",
COUNT(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 2 THEN 1 END) AS "2 day",
COUNT(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 3 THEN 1 END) AS "3 day",
COUNT(CASE WHEN CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 4 THEN 1 END) AS "4 day",
...
FROM tab
WHERE CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE <= 30
You could also put the calculation in a Derived Table, but this just looks simpler:
SELECT
COUNT(CASE WHEN diff = 1 THEN 1 END) AS "1 day",
COUNT(CASE WHEN diff = 2 THEN 1 END) AS "2 day",
COUNT(CASE WHEN diff = 3 THEN 1 END) AS "3 day",
COUNT(CASE WHEN diff = 4 THEN 1 END) AS "4 day"
FROM
(
SELECT CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE AS diff
FROM tab
WHERE diff <= 30
) AS dt
回答2:
Are you looking for this?
WHERE CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE BETWEEN 1 AND 30
I think BETWEEN
is what you want.
来源:https://stackoverflow.com/questions/23527359/sequencing-in-teradata