在SQL查询中组合SUBSTR,COUNT和COUNT

时间:2013-11-29 11:17:04

标签: sql count sum substr

我的查询包含SUBSTRCOUNTSUM,但不起作用。没有数据返回。这是我的问题:

$query="SELECT COUNT(TYPE_A), SUM(HRGPASANG), SUM(HRGABULAN), SUM(HRGATAHUN) 
from namatabel where NIKAM='651290' 
AND (SUBSTR(end_date,7,4)=2013) 
AND SUBSTR(CNTRC_EDATE,4,2)=12) 
AND (TYPE_A='ZBSA'OR TYPE_A='ZMOS' OR TYPE_A='ZCSA')";

3 个答案:

答案 0 :(得分:0)

(SUBSTR(end_date,7,4)= 2013)

你错过了报价吗?

(SUBSTR(end_date,7,4)='2013')

答案 1 :(得分:0)

尝试在日期值上加上引号:

 $query="SELECT COUNT(TYPE_A), SUM(HRGPASANG), SUM(HRGABULAN), SUM(HRGATAHUN)
 FROM namatabel where NIKAM='651290' 
 AND (SUBSTR(end_date,7,4)='2013')
 AND SUBSTR(CNTRC_EDATE,4,2)='12') 
 AND (TYPE_A='ZBSA' OR TYPE_A='ZMOS' 
 OR TYPE_A='ZCSA')";

在这种情况下,201312都应该有引号。

还使用IN()函数代替OR子句,例如:

 $query="SELECT COUNT(TYPE_A), SUM(HRGPASANG), SUM(HRGABULAN), SUM(HRGATAHUN)
 FROM namatabel where NIKAM='651290' 
 AND SUBSTR(end_date,7,4)='2013'
 AND SUBSTR(CNTRC_EDATE,4,2)='12'
 AND TYPE_A IN('ZBSA','ZMOS','ZCSA')";

答案 2 :(得分:0)

您应该使用DATEPART函数来获取正确数量的SQL而不是子字符串。

见下文

SELECT COUNT(TYPE_A), SUM(HRGPASANG), SUM(HRGABULAN), SUM(HRGATAHUN) 
FROM namatabel 
WHERE NIKAM='651290' 
AND DATEPART(YYYY,end_date)=2013 
AND DATEPART(MM,CNTRC_EDATE)=12 
AND TYPE_A IN ('ZBSA','ZMOS','ZCSA')