2017-12-05 7 views
-1

このビューテーブルはSQL Serverにあり、別の列に各レコードの一意のキーにしたいと考えています。ビューのクエリ操作で使用するユニークなキー

個別の列に各レコードの固有のキーを作成する方法はありますか?例

のインデックスのようにこれは、コードビュー

SELECT  'order' AS type, id AS id, id_customer, amount AS debit, 0 AS credit, order_date AS date, '....' AS description 
FROM   dbo.Orders 
UNION ALL 
SELECT  'receipt' AS type, id AS id, id_customer, 0 AS debit, amount AS credit, receipt_date AS date, 'cash' AS description 
FROM   dbo.receipts 

私はこのコード を使用してこのプレゼンテーションを求めていますが作成されますが、私はそれぞれを繰り返して、請求書や領収書と同様のID番号がある問題を抱えています私は一意のキーは、次のコードでの比較をしたいので、二度、それらの

declare @id_customer int 
;with initial as(
    select * 
    from result 
    where id_customer= @id_customer 
),report as(
    select r.id,[balance]=isnull((select sum(b.debit-b.credit) 
       from initial b 
       where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit) 
    from initial r 
) 

select [Operation type] = type, 
     reference_no = r.id, 
     [description], 
     [Debit] = debit, 
     [Credit] = credit, 
     [Balance] = b.balance 
from result r 
inner join report b on b.id = r.id 
where r.id_customer = @id_customer 
order by r.[date] 
+0

の比較仕事をするクエリを追加質問。 –

+0

行番号を尋ねていますか?それ以外の場合は、データを理解せずにキーを作成する方法を教えられません。 – MgSam

+0

ユニークなキーを作りましょうか?各行に固有の値を取得しようとしていますか? NEWID()を使用できます。 –

答えて

-1

あなたは(私が理解したように)、あなたはあなたの選択のためのNEWIDを使用しなければならない新しい一意のキーを使用してレコードを区別したい場合hにするためにUnionAllクエリの一意のキーをaveの:

declare @id_customer int 
;with initial as(
    select * 
    from result 
    where id_customer= @id_customer 
),report as(
    select r.id,[balance]=isnull((select sum(b.debit-b.credit) 
       from initial b 
       where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit) 
    from initial r 
) 

select NEWID(), -- this is a new generated unique key 
     [Operation type] = type, 
     reference_no = r.id, 
     [description], 
     [Debit] = debit, 
     [Credit] = credit, 
     [Balance] = b.balance 
from result r 
inner join report b on b.id = r.id 
where r.id_customer = @id_customer 
order by r.[date] 
+0

sir idを新しい鍵で置き換えたい.'b.id = r.id' –

-1

あなたは、レコードに自動番号を与え、あなたはあなたが尋ねるのを忘れているように見えるそのフィールド

declare @id_customer int 
    ;with 
    result3 as (select ROW_NUMBER() OVER (ORDER BY date ASC) AS Row , * from result), 
    initial as(select * from result3 where id_customer= @id_customer), 
    report as(select r.row,[balance]=isnull((select sum(b.debit-b.credit) 
        from initial b 
        where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit) 
     from initial r 
    ) 

    select 
      row=r.row, 
      [Operation type] = type, 
      reference_no = r.id, 
      [description], 
      [Debit] = debit, 
      [Credit] = credit, 
      [Balance] = b.balance, 
      [date] = [date] 
    from result3 r 
    inner join report b on b.row = r.row 
    where r.id_customer = @id_customer 
    order by r.[date] 
関連する問題