Hive SQL Integer YYYYMM上个月

时间:2018-04-17 11:18:15

标签: sql hadoop hive hiveql

我想创建一个查找过去2个月的SQL语句。

例如:

Select * 
from x
where sampledate<= YYYYMM-2

目前我使用的是:

(year(from_unixtime(unix_timestamp()))*100+month(from_unixtime(unix_timestamp())))-1

但它会在一年的前两个月返回错误的陈述:(

我的想法是用日期计算,然后将其更改为yyyymm整数格式。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

SELECT colomn
FROM table
WHERE date > (SELECT add_months(from_unixtime(unix_timestamp()),-2));

或者您可以使用:

SELECT colomn
FROM table
WHERE date > to_date(SELECT year(add_months(from_unixtime(unix_timestamp()),-2))+month(add_months(from_unixtime(unix_timestamp()),-2)));

与regex&amp; substring结合使用:

SELECT colomn
FROM table
where sampledate>=substr(regexp_replace(add_months(from_unixtime(unix_timestamp()),-2), '-',''),1,6)

获得YYYYMM日期

答案 1 :(得分:0)

如果您想避免以YYYYMM格式转换日期之间的整数,您可以使用数学和CASE语句......

例如YYYYMM % 100将为您提供MM。然后你可以检查它是否为2或更少。如果它是2或更少,扣除100减少一年,并添加12得到月或13或14.然后,扣除2将给你正确的答案。

重新安排,你得到YYYYMM - 2 + (88, if the month is 1 or 2)

sampledate <= YYYYMM - 2 + CASE WHEN YYYYMM % 100 <= 2 THEN 88 ELSE 0 END

更好的想法可能只是重塑您的数据,以便您实际拥有(真实)日期字段,并使用ADD_MONTHS(aRealDate, -2) ...


<强> 编辑:

如果您的实际问题在两个月前&#34;生成{&#34}的YYYYMM值,则扣除您使用 之前的 2个月YEAR()MONTH()函数。

year(  ADD_MONTHS(from_unixtime(unix_timestamp()), -2) )*100
+
month( ADD_MONTHS(from_unixtime(unix_timestamp()), -2) )

答案 2 :(得分:0)

尝试这样的事情。 首先,一个实用程序,用于获取未来/过去n个月的日期:

public Date nMonthsFromDate(Date date, int interval) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    // E.G. to get 2 months ago, add -2
    cal.add(Calendar.MONTH, interval); 
    Date result = cal.getTime();
    return result;
}

对实体的标准查询,此处为成员:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Member> q = cb.createQuery(Member.class);
Root<Member> memberRoot = q.from(Member.class);
Date theDate = nMonthsFromToday(-2);
Predicate pred = cb.greaterThanOrEqualTo(
    memberRoot.<Date>get("timeStamp"), theDate);
q.where(pred);
TypedQuery<Member> theQuery = em.createQuery(q);
String qStr = theQuery
    .unwrap(org.apache.openjpa.persistence.QueryImpl.class)
    .getQueryString();
LOG.info("Query: " + qStr);
List<Member> results = null;
try {
    results = theQuery.getResultList();
} catch (Exception e) {
    LOG.severe(e.getMessage());
    e.printStackTrace();
}
return results;

最后,请注意将日期[java.util.Date]与时间戳[util.sql.Date]进行比较。由于Java中的怪癖,对于等效日期,date.equals(timeStamp)返回true,但是timeStamp.equals(date)返回FALSE。要将两个日期符合java.util.Date:

public java.util.Date getStandardDate(Date date) {
    return new java.util.Date(date.getTime());