我有两张用于 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,它具有不同的板用于消耗的单位数量。
有任何想法吗