将两条记录合并为SQL Server中的一条记录

时间:2017-04-11 04:31:30

标签: sql-server stored-procedures

如何在获取数据时进行分组' Pej。 Pesaka Kecil'和' Pej。 Tanah Daerah'例如:

DECLARE @fMonth AS VARCHAR(20) = '1'
DECLARE @fYear AS VARCHAR(5) = '2017'
DECLARE @tMonth AS VARCHAR(20) = '5'
DECLARE @tYear AS VARCHAR(5) = '2017'


select * from (
    select @fMonth AS fMonth, @fYear AS fYear, @tMonth AS tMonth, @tYear AS tYear,
    (case when Description in ('Pej. Pesaka Kecil', 'Pej. Tanah Daerah') then 'JKPTG'
                 else Description
            end) as description, [state_desc]


    from B_Requestor as main
    left join B_Party as b on  main.requestorid = b.requestorid
    left join B_BlueCard as blue on b.partyid = blue.partyid and YEAR(blue.AppliedDate) = @fYear and blue.CardType = 'Form C'
    group by  state, category, (case when description in ('Pej. Pesaka Kecil', 'Pej. Tanah Daerah') then 'JKPTG' else Description 
      end) ,[state_desc]
) t
    order by  (case when description =  'Amanah Raya Berhad' then 1
                                       when description = 'Mahkamah Tinggi' then 2
                                       when description = 'JKPTG' then 3
                                       END) ASC, [state_desc]

当前输出的结果正确,但需要根据DescriptionState_desc进行分组。但是想要保留输出中的所有当前列。

谢谢你们。

1 个答案:

答案 0 :(得分:1)

select MAX(fMonth),MAX(fYear),MAX(tMonth),MAX(tYear),[description],[state_desc] from (
    select @fMonth AS fMonth, @fYear AS fYear, @tMonth AS tMonth, @tYear AS tYear,
    (case when Description in ('Pej. Pesaka Kecil', 'Pej. Tanah Daerah') then 'JKPTG'
                 else Description
            end) as description, [state_desc]
    from BKM_Requestor as main
    left join BKM_Party as b on  main.requestorid = b.requestorid
    left join BKM_BlueCard as blue on b.partyid = blue.partyid and YEAR(blue.AppliedDate) = @fYear and blue.CardType = 'Form C'
    group by  state, category, (case when description in ('Pej. Pesaka Kecil', 'Pej. Tanah Daerah') then 'JKPTG' else Description 
      end) ,[state_desc]
) t
group by [description],[state_desc]
    order by  (case when description =  'Amanah Raya Berhad' then 1
                                       when description = 'Mahkamah Tinggi' then 2
                                       when description = 'JKPTG' then 3
                                       END) ASC, [state_desc]