3

サンプルテーブル

CustomerId | VoucherId | CategoryId | StartDate | EndDate
-------------------------------------------------------------
        10 |         1 |          1 | 2013-09-01| 2013-09-30
        10 |         1 |          2 | 2013-09-01| 2013-09-30
        11 |         2 |          1 | 2013-09-01| 2013-11-30
        11 |         2 |          2 | 2013-09-01| 2013-11-30
        11 |         2 |          3 | 2013-09-01| 2013-11-30
        10 |         3 |          1 | 2013-10-01| 2013-12-31
        10 |         3 |          2 | 2013-10-01| 2013-12-31
        11 |         4 |          1 | 2013-12-01| 2014-04-30

上記のサンプル レコードで、顧客のバウチャーがカバーする合計月数を調べたい

フォームの出力が必要です

CustomerId | Months
--------------------
        10 | 4
        11 | 8

問題は、バウチャーが異なる CategoryIds に対して複数の行を持つことができることです...

DATEDIFF(MM, StartDate, EndDate) + 1 としてバウチャーの対象となる月を計算しました...

SUM(DATEDIFF(MM, StartDate, EndDate)) GROUP BY VoucherId, StartDate, EndDate を適用すると、VoucherId に複数の行があるため、間違った結果が返されます....

私はこのようなものを得ます...

CustomerId | Months
--------------------
        10 | 8
        11 | 14

このシナリオでは CategoryId は役に立ちません

ありがとう

4

4 に答える 4

4

実際、あなたの場合(各カテゴリの期間が等しい場合)、次のクエリを使用できます。

with cte as (
    select distinct
        CustomerId, StartDate, EndDate
    from Table1
)
select CustomerId, sum(datediff(mm, StartDate, EndDate) + 1) as diff
from cte
group by CustomerId

sql fiddle demo

于 2013-10-11T17:00:54.563 に答える
0

クエリで不要な列をグループ化しています。

SQLフィドル!

于 2013-10-11T17:00:45.473 に答える