sql小结

1 group by 用法

group by 是用来分组的,当使用group by时要注意以下几点:

1>select后面不能有* ,如果需要全部列出需要一项项写出来

如:SELECT HJFZC.SP_ID, HJFZC.SPCODE, HJFZC.BARCODE,HJFZC.ZL

而不能写成SELECT HJFZC.*

2>group by 后面不能有函数,而且所有SELECT后面的非函数列都要在group by后面列出

如:GROUP BY HJFZC.ZL, HJFZC.SP_ID, HJFZC.SPCODE, HJFZC.BARCODE

2 order by用法

order by是用来排序的,默认是ase,desc是表示降序。当前面的group by时使用就要注意了:

1>当分组和排序不是同一列时,要先写上group by 的列再写上要排序的列。

ORDER BY HJFZC.ZL, HJFZC.XSJE DESC;

2>order by 后面不能有列的别名。

SELECT HJFMX.ZL, HJFMX.ZLNAME, Sum(HJFMX.XSJE) AS ZJE, Sum(HJFMX.ML) AS ZML, (ZML/ZJE) AS PJMLL
FROM HJFMX
WHERE (((HJFMX.DL)<>"03"))
GROUP BY HJFMX.ZL, HJFMX.ZLNAME
ORDER BY Sum(HJFMX.ML)/Sum(HJFMX.XSJE) DESC;

如果写成ORDER BY PJMLL DESC是不行的。

3 多表关联

1)查出HJFMX表中SP_ID包含在TPSPID的SP_ID列所有记录==方法一
 

SELECT HJFMX.*
FROM HJFMX INNER JOIN TPSPID ON HJFMX.SP_ID=TPSPID.SP_ID
WHERE (((HJFMX.DL)<>"03") AND ((HJFMX.ZLSPBJ)=0))
ORDER BY HJFMX.XSJE DESC;

2)查出HJFMX表中SP_ID包含在TPSPID的SP_ID列所有记录==方法二

SELECT HJFMX.*
FROM HJFMX, TPSPID
WHERE HJFMX.SP_ID=TPSPID.SP_ID
ORDER BY HJFMX.XSJE DESC;
3)查出HJFMX表中SP_ID不包含在TPSPID的SP_ID列所有记录

SELECT HJFMX.*
FROM HJFMX
WHERE HJFMX.SP_ID NOT IN (SELECT TPSPID.SP_ID FROM TPSPID)
ORDER BY HJFMX.XSJE DESC;
 

你可能感兴趣的:(sql,数据库,职场,休闲,sql小结)