SQL Server加入AND QUERY问题

时间:2013-02-18 07:41:34

标签: sql sql-server database

我有一个表billing_history,其中包含以下字段

CREATE TABLE [dbo].[BILLING_HISTORY2](
[ID] [int] IDENTITY(1,1) NOT NULL,
[READING_MONTH_YEAR] [date] NULL,
[READING] [int] NULL,
[CONSUMER_ID] [int] NULL,
[payment_status] [bit] NOT NULL
) 

http://www.sqlfiddle.com/#!3/892e0/5

以下查询返回消费者的最高付费和最高未付款值

SELECT MAX(READING) AS 'MAXIMUM_PAID_READING',consumer_id from billing_history2
where payment_status=0 GROUP BY consumer_id;

SELECT MAX(READING) AS 'MAXIMUM_UNPAID_READING',consumer_id from billing_history2
where payment_status=1 GROUP BY consumer_id;

然而,当我加入它们从MAXIMUM_UNPAID_READING中减去MAXIMUM_PAID_READING以获得当前读数时,通过加入上述两个查询,它会返回所有那些匹配的consumer_id的记录。因此,如果消费者尚未支付任何账单,则在PAID_READING中将省略id,因此INNER JOIN不会返回任何结果。如果我使用FULL OUTER JOIN,它将返回所有记录,但将差异设置为NULL。

我需要通过从之前的未付款USAGE中减去客户的当前USAGE来找出它。

我如何以这样一种方式加入这两个查询,即无论该人是否已经支付过账单,都会发现产生的差异。

3 个答案:

答案 0 :(得分:1)

不要加入他们。

SELECT
    MAX(CASE WHEN payment_status=0 THEN READING ELSE NULL END) AS 'MAXIMUM_PAID_READING',
    MAX(CASE WHEN payment_status=1 THEN READING ELSE NULL END) AS 'MAXIMUM_UNPAID_READING',

    MAX(CASE WHEN payment_status=0 THEN READING ELSE NULL END)
     - MAX(CASE WHEN payment_status=1 THEN READING ELSE NULL END)
        AS 'DIFF_READING',

    consumer_id from billing_history2
GROUP BY consumer_id;

如果要从MAX函数处理NULL值,请使用ISNULL函数:

SELECT
    ISNULL(MAX(CASE WHEN payment_status=0 THEN READING ELSE NULL END),0) AS 'MAXIMUM_PAID_READING',
    ISNULL(MAX(CASE WHEN payment_status=1 THEN READING ELSE NULL END),0) AS 'MAXIMUM_UNPAID_READING',

    ISNULL(MAX(CASE WHEN payment_status=0 THEN READING ELSE NULL END),0)
     - ISNULL(MAX(CASE WHEN payment_status=1 THEN READING ELSE NULL END),0)
        AS 'DIFF_READING',

    consumer_id from billing_history2
GROUP BY consumer_id;

答案 1 :(得分:0)

可以使用左外连接,但在最大值上使用isnull。

例如:

max(...) - isnull(max(...),0) as ...

答案 2 :(得分:0)

在您的情况下,有必要使用CASE表达式

SELECT CONSUMER_ID,
       MAX(CASE WHEN payment_status = 0 THEN READING ELSE 0 END) AS 'MAXIMUM_PAID_READING',
       MAX(CASE WHEN payment_status = 1 THEN READING ELSE 0 END) AS 'MAXIMUM_UNPAID_READING', 
       MAX(CASE WHEN payment_status = 0 THEN READING ELSE 0 END) - 
       MAX(CASE WHEN payment_status = 1 THEN READING ELSE 0 END) AS diff
FROM billing_history2
GROUP BY consumer_id

SQLFiddle上的演示