SELECT t1.id, t1.[kh] AS '客户', t1.[lrsj] AS '录入时间', t1.[htbh] AS '合同编号', t1.[rq] AS '签订日期', t1.[htqsrq] AS '起始日期', t1.[htjzrq] AS '截止日期', t1.[zjey] AS '总金额', t1.[hjzld] AS '总吨数', t1.[lrsj] AS '创建时间', t1.[chpt] AS '撮合平台', CAST ( t1.[htwj] AS VARCHAR ( MAX ) ) AS '合同文件', STUFF( ( SELECT ',' + CONVERT ( VARCHAR, CASE WHEN ISNUMERIC( REPLACE( t2.ppcs, ',', '' ) ) = 1 THEN CAST ( REPLACE( t2.ppcs, ',', '' ) AS FLOAT ) END ) FROM uf_xsht_dt1 t2 WHERE t1.id = t2.mainid FOR XML PATH ( '' ) ), 1, 1, '' ) AS '品牌', STUFF( ( SELECT ' ' + CONVERT ( VARCHAR, CASE WHEN ISNUMERIC( REPLACE( t2.hsdjyd, ' ', '' ) ) = 1 THEN CAST ( REPLACE( t2.hsdjyd, ' ', '' ) AS FLOAT ) END ) FROM uf_xsht_dt1 t2 WHERE t1.id = t2.mainid FOR XML PATH ( '' ) ), 1, 1, '' ) AS '销售单价', (SELECT SUM ( sjfk ) from uf_xshksj2 WHERE cght=t1.id ) AS '实际已收', (SELECT SUM ( hkje ) from uf_xshksj2 WHERE cght=t1.id ) AS '已收货款', ( SELECT SUM( sjfk ) FROM uf_xshksj2 WHERE kxlx = 0 AND cght = t1.id ) AS '订金', CASE WHEN ((SELECT SUM (ISNULL( hkje,0) ) from uf_xshksj2 WHERE cght=t1.id ) + (SELECT SUM(ISNULL(sjfk, 0)) FROM uf_xshksj2 WHERE kxlx = 0 AND cght = t1.id)) < t1.[zjey] THEN ((SELECT SUM ( ISNULL( hkje,0)) from uf_xshksj2 WHERE cght=t1.id ) / t1.[zjey]) ELSE ((SELECT SUM ( ISNULL( hkje,0) ) from uf_xshksj2 WHERE cght=t1.id ) + (SELECT SUM(ISNULL(sjfk, 0)) FROM uf_xshksj2 WHERE kxlx = 0 AND cght = t1.id)) / t1.[zjey] END AS '已收比例' FROM uf_xsht t1 INNER JOIN uf_xsht_dt1 t2 ON t1.id = t2.mainid LEFT JOIN uf_xshksj2 t3 ON t1.id = t3.cght GROUP BY t1.id, t1.[kh], t1.[lrsj], t1.[htbh], t1.[rq], t1.[htqsrq], t1.[htjzrq], t1.[zjey], t1.[hjzld], t1.[chpt], CAST ( t1.[htwj] AS VARCHAR ( MAX ) )中为什么已付比例除了第一个有值 ,其他却显示空值
时间: 2024-01-22 16:03:19 浏览: 152
EL表达式访问内置方法
根据你提供的查询语句,我注意到在计算已付比例的部分使用了一个 CASE 表达式。首先,我想强调该查询语句中的子查询是分开计算的,每个子查询都会返回一个结果。而在 CASE 表达式中,只有第一个子查询的结果被用于计算已付比例,而其他子查询的结果没有被使用。这就是为什么其他部分显示为空值的原因。
如果你希望所有子查询的结果都被用于计算已付比例,你可以将这些子查询的结果提前计算并存储为临时表或使用内联视图。然后,在 CASE 表达式中引用这些临时表或内联视图,确保计算已付比例时所有子查询的结果都被考虑进去。
以下是一个示例,展示如何使用内联视图来计算已付比例:
```sql
SELECT
t1.id,
t1.[kh] AS '客户',
t1.[lrsj] AS '录入时间',
-- 省略其他字段...
CASE
WHEN (t3.已收货款 + t3.订金) < t1.[zjey] THEN
(t3.已收货款 / t1.[zjey])
ELSE
(t3.已收货款 + t3.订金) / t1.[zjey]
END AS '已收比例'
FROM
uf_xsht t1
INNER JOIN uf_xsht_dt1 t2 ON t1.id = t2.mainid
LEFT JOIN (
SELECT
cght,
SUM(ISNULL(hkje, 0)) AS 已收货款,
SUM(CASE WHEN kxlx = 0 THEN ISNULL(sjfk, 0) ELSE 0 END) AS 订金
FROM
uf_xshksj2
GROUP BY
cght
) t3 ON t1.id = t3.cght;
```
在上述示例中,我使用了一个内联视图(子查询)来计算已收货款和订金的总和,并将其命名为 t3。然后,在 CASE 表达式中引用了 t3 中的已收货款和订金字段,确保计算已付比例时考虑了所有的子查询结果。
请根据你的实际需求和数据结构进行适当的调整。希望这能帮到你!
阅读全文