2017-12-05 3 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

당신이 물어 잊어 버린 것 같다 해당 필드에 비교 작업을 수행합니다 UnionAll 쿼리에 대한 고유 키 집결지 문제. –

+0

행 번호를 묻는 중입니까? 그렇지 않으면 데이터를 이해하지 않고 키를 만드는 방법을 알 수 없습니다. – MgSam

+0

고유 한 키를 만드시겠습니까? 각 행에 대해 고유 한 값을 얻으려고하고 있습니까? NEWID()를 사용할 수 있습니다. –

답변

-1

당신이 (내가 이해) 다음 선택에 대한 NEWID을 사용하여야한다 새로운 고유 키와 기록을 구별하려면 h에 순서대로

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]