在Teradata中排序

时间:2014-05-07 20:06:16

标签: sql sequence teradata

我想创建一个SELECT查询,该查询产生30个字段长和1个记录厚度的视图。如果我们正在计算标题,请记录2条记录。

相关较大查询的具体部分是:

WHERE CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 1

这会产生所需的结果 - 记录EVENT_TIMESTAMP和CONTRACT_EFFECTIVE_DATE之间的天数为1。

但是我这样做了30天。类似的东西:

WHERE CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE = 1:30

这可能吗?我可以剪切n次粘贴查询30次并将数字1更改为相应的值。但肯定有更好的方法吗?

结果看起来像:

1 day   2 day   3 day   4 day
10       11       8      14

2 个答案:

答案 0 :(得分:3)

那是另一个PIVOT查询,又有很多剪切和粘贴。

假设您要计算与每天范围匹配的行数:

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

您也可以将计算放在派生表中,但这只是看起来更简单:

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

答案 1 :(得分:1)

你在找这个吗?

WHERE CAST(EVENT_TIMESTAMP AS DATE) - CONTRACT_EFFECTIVE_DATE BETWEEN 1 AND 30

我认为BETWEEN就是你想要的。