SQL错误(1054)未知列

时间:2012-09-06 17:52:47

标签: sql

我在这里有这个很长的SQL查询..

SELECT c.clientid, c.clientname, c.billingdate, 
case when (select ifnull(sum(total), 0) from invoice i
where i.client = c.clientid and i.isdeleted = 0) - (select ifnull(sum(p.amount), 0) from payment p inner join invoice i on p.invoice = i.invoiceid
where i.client = c.clientid and i.isdeleted = 0) < 0 and i.date < '2012-01-01' then (select ii.total from invoice ii where ii.client = c.clientid order by ii.invoiceid desc limit 1)  else (select ifnull(sum(total), 0) from invoice i
where i.client = c.clientid and i.isdeleted = 0) - (select ifnull(sum(p.amount), 0) from payment p inner join invoice i on p.invoice = i.invoiceid
where i.client = c.clientid and i.isdeleted = 0) end as remaining,
case c.isactive+0
        when '1' then 'Stop'
        else 'Start' 
        end as Active
FROM client c 
ORDER BY clientname

我在第i.date < '2012-01-01'行中遇到错误,说明i.date是字段列表中的未知列...我该如何解决此问题?

谢谢, Ĵ

2 个答案:

答案 0 :(得分:4)

您在子查询中使用alias i范围内的(select ifnull(sum(total), 0) from invoice i where i.client = c.clientid and i.isdeleted = 0)

()

使用and i.date < '2012-01-01'

你应该改变包括这个:

SELECT c.clientid, c.clientname, c.billingdate, 
case when (select ifnull(sum(total), 0) from invoice i
where i.client = c.clientid and i.isdeleted = 0 and i.date < '2012-01-01' ) - (select ifnull(sum(p.amount), 0) from payment p inner join invoice i on p.invoice = i.invoiceid
where i.client = c.clientid and i.isdeleted = 0 and i.date < '2012-01-01' ) < 0 then (select ii.total from invoice ii where ii.client = c.clientid order by ii.invoiceid desc limit 1)  else (select ifnull(sum(total), 0) from invoice i
where i.client = c.clientid and i.isdeleted = 0) - (select ifnull(sum(p.amount), 0) from payment p inner join invoice i on p.invoice = i.invoiceid
where i.client = c.clientid and i.isdeleted = 0) end as remaining,
case c.isactive+0
        when '1' then 'Stop'
        else 'Start' 
        end as Active
FROM client c 
ORDER BY clientname
选择

中的

{{1}}

答案 1 :(得分:0)

你是i.date在子查询之外。就在这里

SELECT c.clientid, c.clientname, c.billingdate, 
CASE WHEN 
    (select ifnull(sum(total), 0) from invoice i where i.client = c.clientid and i.isdeleted = 0)
    - 
    (select ifnull(sum(p.amount), 0) from payment p inner join invoice i on p.invoice = i.invoiceid where i.client = c.clientid and i.isdeleted = 0)
    < 0 
    and i.date < '2012-01-01'  -- THIS IS NOT PART OF THE SUBQUERY
THEN 
    (select ii.total from invoice ii where ii.client = c.clientid order by ii.invoiceid desc limit 1)  
ELSE 
    (select ifnull(sum(total), 0) from invoice i where i.client = c.clientid and i.isdeleted = 0) - (select ifnull(sum(p.amount), 0) from payment p inner join invoice i on p.invoice = i.invoiceid where i.client = c.clientid and i.isdeleted = 0) 
END as remaining,
case c.isactive+0
        when '1' then 'Stop'
        else 'Start' 
        end as Active
FROM client c 
ORDER BY clientname