2

毎月の請求情報を保存するテーブルがあります。

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

Consumer_idは、コンシューマー詳細テーブルを参照する外部キーです。

私が欲しいのは、前月の測定値からすべての顧客の現在の測定値を差し引くことです。これにより、現在の請求書が生成されます。何か案は。

4

1 に答える 1

4

これに似たものを使用して、返したい月/年の値を置き換えることができます。

select b1.consumer_id,
  sum(b1.reading - isnull(b2.reading, 0)) Total
from billing_history b1
left join billing_history b2
  on b1.consumer_id = b2.consumer_id
  and month(b2.reading_date) =12
  and year(b2.reading_date) = 2012
where month(b1.reading_date) = 1
  and year(b1.reading_date) = 2013
group by b1.consumer_id;

SQL FiddlewithDemoを参照してください。

monthとの値を渡さずyearに検索し、現在/前の月のみが必要な場合は、CTEを使用して次のようなものを使用できます。

;with cur as
(
  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())
)
select c.consumer_id, 
  sum(c.reading - isnull(pre.reading, 0)) TotalReading
from cur 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

SQL FiddlewithDemoを参照してください

このバージョンでは、現在/前の月と年の両方の値が使用されます。CTE構文に精通していない場合は、次のように書くこともできます。

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;

SQL FiddlewithDemoを参照してください。

クエリでわかるように、集計関数SUM()とを使用GROUP BYしましたconsumer_id。私はあなたが顧客ごとに複数の読書をした場合にこれをしました。1か月に1回しか読み取れないことがわかっている場合は、集計を削除できます。

于 2013-02-05T10:10:38.957 に答える