SELECT c.REGION,COUNT(*)COUNT
FROM OAS_CONTRACT a
INNER JOIN OAS_CONTRACT_OFFICES b ON a.CONTRACT_ID=b.CONTRACT_ID
INNER JOIN OAS_CONTRACT_OFFICES_DETAIL c ON b.T2_CODE = c.T2_CODE
WHERE (a.EXPIRY_DATE >= SYSDATE)
GROUP BY c.REGION ORDER BY c.REGION
在上面的Oracle查询WHERE子句中没有任何效果。它还返回EXPIRY_DATE < SYSDATE
(过期合同)的合同。我不知道如何安排以上查询。请帮助我,我被卡住了!
OAS_CONTRACT
CONTRACT_ID EXPIRY_DATE
541 11/14/2017
561 11/14/2014
查询返回两者它应该只返回541,因为它是未过期的。
以下查询返回非过期合同
SELECT * FROM OAS_CONTRACT a WHERE (a.EXPIRY_DATE >= SYSDATE)
并且此查询返回过期的合同
SELECT * FROM OAS_CONTRACT a WHERE (a.EXPIRY_DATE < SYSDATE)
但是当我内部加入表时,我没有得到所需的结果。下面的查询返回过期和未过期的合同。
SELECT c.REGION,COUNT(*)COUNT
FROM OAS_CONTRACT a
INNER JOIN OAS_CONTRACT_OFFICES b ON a.CONTRACT_ID=b.CONTRACT_ID
INNER JOIN OAS_CONTRACT_OFFICES_DETAIL c ON b.T2_CODE = c.T2_CODE
WHERE (a.EXPIRY_DATE >= SYSDATE)
GROUP BY c.REGION ORDER BY c.REGION
我在这里添加更多细节以澄清我面临的问题。
我有以下表格:
CREATE TABLE OAS_CONTRACT
(
CONTRACT_ID NUMBER NOT NULL,
CATEGORY VARCHAR2(200 BYTE),
EXPIRY_DATE DATE)
CREATE TABLE OAS_CONTRACT_OFFICES
(
CONTRACT_ID NUMBER NOT NULL,
T2_CODE VARCHAR2(200 BYTE)
)
CREATE TABLE OAS_CONTRACT_OFFICES_DETAIL
(
T2_CODE VARCHAR2(200 BYTE),
REGION VARCHAR2(200 BYTE)
)
--NON-EXPIRED
INSERT INTO OAS_CONTRACT VALUES (10,'Test',SYSDATE+60);
--EXPIRED
INSERT INTO OAS_CONTRACT VALUES (11,'Test2',SYSDATE-60);
INSERT INTO OAS_CONTRACT_OFFICES (10,'ABC123');
INSERT INTO OAS_CONTRACT_OFFICES (11,'ABC124');
INSERT INTO OAS_CONTRACT_OFFICES_DETAIL ('ABC123','HQ-1');
INSERT INTO OAS_CONTRACT_OFFICES_DETAIL ('ABC124','HQ-2');
我需要计算按地区分组的未过期合约
REGION COUNT
HQ-1 1
但我得到了这个
REGION COUNT
HQ-1 1
HQ-2 1
答案 0 :(得分:1)
我猜你希望min()
的{{1}}晚于sysdate:
EXPIRY_DATE
作为提示:使用表别名是一件好事。使它们成为表名的缩写使查询更容易理解。我建议您使用SELECT c.REGION, COUNT(*) as COUNT
FROM OAS_CONTRACT a INNER JOIN
OAS_CONTRACT_OFFICES b
ON a.CONTRACT_ID = b.CONTRACT_ID INNER JOIN
OAS_CONTRACT_OFFICES_DETAIL c
ON b.T2_CODE = c.T2_CODE
GROUP BY c.REGION
HAVING MIN(a.EXPIRY_DATE) >= SYSDATE
ORDER BY c.REGION;
,c
和co
代替od
,a
和b
。
编辑:
c
未以Oracle日期的标准格式打印。我怀疑它被存储为字符串 - 坏,坏,坏。如果是这样,那么这可能是您需要的修复:
EXPIRY_DATE
编辑II:
在您的示例数据中,似乎WHERE to_date(a.EXPIRY_DATE, 'MM/DD/YYYY') >= SYSDATE
可能是EXPIRY_DATE
。如果是这样,那么试试这个NULL
条款:
WHERE
答案 1 :(得分:0)
使用MYSQL的NOW()函数,而不是sysdate:
SELECT c.REGION,COUNT(*)COUNT FROM OAS_CONTRACT a
INNER JOIN OAS_CONTRACT_OFFICES b ON
a.CONTRACT_ID=b.CONTRACT_ID
INNER JOIN OAS_CONTRACT_OFFICES_DETAIL c ON
b.T2_CODE = c.T2_CODE
WHERE (a.EXPIRY_DATE >= NOW())
GROUP BY c.REGION ORDER BY c.REGION
在SQL小提琴中here
尝试