1

我有两张用于 Microhydel 应用程序的表,一张包含消费者的月度账单记录,从中生成月度客户账单。

CREATE TABLE billing_history(
    [id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [reading_date] [date] NOT NULL,
    [reading_year] [smallint] NULL,
    [reading] [numeric](18, 0) NOT NULL,
    [consumer_id] [int] NOT NULL,
    [paid_amount] [numeric](18, 0) NULL)

我有另一个表格,它为商业和家庭用户存储单位成本的不同板。

CREATE TABLE [rate_list](
    [flag] [varchar](50) NULL,
    [limit] [numeric](18, 0) NOT NULL,
    [price] [numeric](18, 0) NOT NULL,
    [service_charges] [numeric](18, 0) NOT NULL,
    [surcharge] [numeric](18, 0) NOT NULL
) 

例如,对于每月消耗 50 单位或更少电力的国内客户,与消耗相同电量的商业客户的收费不同。同样,在此平板上消耗的单位将对其应用另一个费率。

感谢@bluefeet,我已经有了使用该查询生成从第一个表中消耗的单位数的查询

select c.consumer_id, 
  sum(c.reading - isnull(pre.reading, 0)) TotalReading
from
(
  select consumer_id,
    reading,
    month(getdate()) curMonth,
    year(getdate()) curYear,
    case when month(getdate()) = 1 then 12 else month(getdate()) -1 end preMonth,
    case when month(getdate()) = 1 then year(getdate())-1 else year(getdate()) end preYear
  from billing_history
  where month(reading_date) = month(getdate())
    and year(reading_date) = year(getdate())
) c
left join billing_history pre
  on c.consumer_id = pre.consumer_id
  and month(pre.reading_date) = c.preMonth
  and year(pre.reading_date) = c.preYear
group by c.consumer_id;

但是,我需要为每个客户生成每月账单,以便例如根据 rate_list 表中的费率。这里的关键是 DOMESTIC/COMMERCIAL,它具有不同的板用于消耗的单位数量。

有任何想法吗

4

1 回答 1

1

对我的回答发表一些评论。

首先,我不确定type_of_connection标志在您发布的SQL Fiddle中的位置,因此我将其添加到Consumers.

其次,我认为您需要更改price_list2表格以包含limit价格的开始值和结束值。否则很难确定每个消费者的价格。

我使用了下price_list2表,其中将包含每个限制的开始/结束值:

CREATE TABLE [price_list2](
    [flag] [varchar](50) NULL,
    [limitStart] [numeric](18, 0) NOT NULL,
    [limitEnd] [numeric](18, 0) NOT NULL,
    [price] [numeric](18, 0) NOT NULL,
    [service_charges] [numeric](18, 0) NOT NULL,
    [surcharge] [numeric](18, 0) NOT NULL);

在查询中,使用您发布的表格和原始查询,您应该能够使用如下内容:

select c.consumer_id,
  r.totalreading * p.price TotalBill
from Consumers c
inner join
(
  select c.consumer_id, 
    sum(c.reading - isnull(pre.reading, 0)) TotalReading
  from
  (
    select consumer_id,
      reading,
      month(getdate()) curMonth,
      year(getdate()) curYear,
      case when month(getdate()) = 1 then 12 else month(getdate()) -1 end preMonth,
      case when month(getdate()) = 1 then year(getdate())-1 else year(getdate()) end preYear
    from billing_history
    where month(reading_date) = month(getdate())
      and year(reading_date) = year(getdate())
  ) c
  left join billing_history pre
    on c.consumer_id = pre.consumer_id
    and month(pre.reading_date) = c.preMonth
    and year(pre.reading_date) = c.preYear
  group by c.consumer_id
) r
  on c.consumer_id = r.consumer_id
inner join price_list2 p
  on c.type_of_connection = p.flag
  and r.totalreading between p.limitStart and p.limitEnd

请参阅带有演示的 SQL Fiddle

正如您在加入price_list2表格时所看到的那样,我正在加入限制的开始/结束范围。这使您可以确定账单应该使用什么价格。

于 2013-02-05T19:25:57.777 回答