我们在做sql查询的时候,有时候需要将查询的列作为表名,去引用,然后再次查询
declare @table_name varchar(20)
select @table_name=table_name from a where <条件>
exec('select * from '+@a)
此sql其实就是先将sql拼接成字符串,然后再将字符串转成sql指令,如果查询到的结果只有一
列的时候,我们可以这样做,如果
@table_name的值有多个,则无法运用此方法
但是,如果碰到这种情况,我们查询的表名并不只有一列,而是多列,则无法运用此方法
这个时候,我们可以采用union ,通过关联不同的表名,来取到对应表的数据,然后再
将所有数据拼接起来,得到最终的结果
SELECT
A.业务号 AS '业务号',
A.提单号 AS '提单号',
A.委托方KID AS '委托方KID',
A.货主KID AS '货主KID',
CAST(A.计费吨 as decimal(20,3)) AS '计费吨',
A.收付类型 AS '收付类型',
convert(varchar(10),A.业务日期,120) AS '业务日期',
CAST(A.实际金额 as decimal(20,2)) AS '实际金额',
A.币种 AS '币种'
FROM (
SELECT ASN.ORDER_NO AS '业务号',
ASN.BL_NO AS '提单号',
EXT.CORPORATION_ID AS '委托方KID',
CUS.CORPORATION_ID AS '货主KID',
CASE WHEN ASN.GROSS_WEIGHT>ASN.VOLUME THEN ASN.GROSS_WEIGHT ELSE ASN.VOLUME END AS '计费吨',
CASE WHEN F.AR_AP='AR' THEN '应收' ELSE '应付' END AS '收付类型',
ASN.FINISHED_TIME AS '业务日期',--记账日期
F.ACTUAL_AMOUNT AS '实际金额',
F.ORGIANL_CURRENCY AS '币种'
FROM F_CHARGE F
INNER JOIN WMS_ASN ASN
ON ASN.KID=F.JOB_ID
INNER JOIN D_CORPORATION_EXT CUS --货主
ON CUS.KID=ASN.CUSTOMER_ID
INNER JOIN D_CORPORATION_EXT EXT --委托方
ON EXT.KID=ASN.CONSIGNER
WHERE F.JOB_TYPE='WMS_ASN'
UNION ALL
SELECT CDO.ORDER_NO AS '业务号',
CDO.BL_NO AS '提单号',
EXT.CORPORATION_ID AS '委托方KID',
CUS.CORPORATION_ID AS '货主KID',
CASE WHEN CDO.GROSS_WEIGHT>CDO.VOLUME THEN CDO.GROSS_WEIGHT ELSE CDO.VOLUME END AS '计费吨',
CASE WHEN F.AR_AP='AR' THEN '应收' ELSE '应付' END AS '收付类型',
CDO.FINISHED_TIME AS '业务日期',--记账日期
F.ACTUAL_AMOUNT AS '实际金额',
F.ORGIANL_CURRENCY AS '币种'
FROM F_CHARGE F
INNER JOIN WMS_CDO CDO
ON CDO.KID=F.JOB_ID
INNER JOIN D_CORPORATION_EXT CUS --货主
ON CUS.KID=CDO.CUSTOMER_ID
INNER JOIN D_CORPORATION_EXT EXT --委托方
ON EXT.KID=CDO.CONSIGNER
WHERE F.JOB_TYPE='WMS_CDO'
) AS A
ORDER BY
A.业务号,
A.提单号,
A.委托方KID,
A.货主KID
在此sql中,其实F_CHARGE表中的JOB_TYPE里面存的是表名,JOB_ID里面存的是
表对应的ID,我们需要根据不同的JOB_TYPE,从不同表里面取到不同的数据,这个
时候,我们就可以通过不同的表名,来union不同的语句,最后就不同的查询列拼
接起来得到最终结果。