从当前月份获取记录

时间:2013-10-29 11:06:30

标签: sql oracle

我试图使用以下查询从购物车表中提取TOTAL_PRICE。目前,它将从过去30天内获取TOTAL_PRICE。但我需要修改查询以获取当前月份的TOTAL_PRICE。 即,PURCHASED_DATE应该在当月的1到30/31之间。

SELECT TOTAL_PRICE
FROM CUST_CART_TABLE
WHERE USER_ID      = '"+userId+"'
AND (PURCHASED_DATE BETWEEN TO_DATE(SYSDATE-30, 'DD-MM-YY') AND TO_DATE(SYSDATE,'DD-MM-YY')

5 个答案:

答案 0 :(得分:2)

您可以使用TRUNC和LAST_DAY:

SELECT TOTAL_PRICE
FROM CUST_CART_TABLE
WHERE USER_ID      = '"+userId+"'
AND (TRUNC(PURCHASED_DATE) BETWEEN TRUNC(SYSDATE, 'MM') AND TRUNC(LAST_DAY(SYSDATE)));

答案 1 :(得分:2)

你可以尝试这个 -

SELECT TOTAL_PRICE
    FROM CUST_CART_TABLE
    WHERE USER_ID      = '"+userId+"'
AND TRUNC(PURCHASED_DATE,'MONTH') = TRUNC(SYSDATE,'MONTH');

它会返回当月的记录。

答案 2 :(得分:1)

请尝试:

SELECT TOTAL_PRICE
FROM CUST_CART_TABLE
WHERE USER_ID='"+userId+"' AND 
TRUNC(PURCHASED_DATE) BETWEEN LAST_DAY(ADD_MONTHS(SYSDATE,-1))+1 AND 
                        LAST_DAY(SYSDATE)

答案 3 :(得分:1)

    SELECT TOTAL_PRICE
    FROM CUST_CART_TABLE
    WHERE USER_ID      = '"+userId+"'
    AND (PURCHASED_DATE BETWEEN 
SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0) 
AND
 SELECT DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0))

答案 4 :(得分:1)

只需比较月份,即'mm'与'yyyy'组合:

SELECT TOTAL_PRICE
FROM CUST_CART_TABLE
WHERE USER_ID = '"+userId+"'
AND TO_CHAR(PURCHASED_DATE,'yyyymm') = TO_CHAR(SYSDATE,'yyyymm');