如何在一行SQL中合并几行

时间:2018-07-31 09:18:49

标签: sql sql-server tsql

我有一个如下所示的表:

enter image description here

我希望看到这样的结果:

enter image description here

ContractType列中的值取决于大小写:

Null - 'Not singed',
1 - 'Postponed',
2 - 'Signed'.

如何在SQL中将其组合?

UPD:对不起,造成混乱。我希望看到的结果是标志:合同是否签署。

5 个答案:

答案 0 :(得分:2)

样本数据

DECLARE @t TABLE (PropertyId INT, ContractTypeId INT)
INSERT INTO @t
(
    PropertyId
    ,ContractTypeId
)
VALUES
(160, NULL), (160, 1), (160, 2) , (165, NULL), (170, 1)


SELECT 
     X.PropertyId
    ,ContractType   =   CASE
                            WHEN X.ContractType IS NULL THEN 'Not Signed'
                            WHEN X.ContractType = 1 THEN 'Postponed'
                            WHEN X.ContractType = 2 THEN 'Signed'
                        END

FROM @t T
INNER JOIN(
    SELECT
         T.PropertyId
        ,ContractType = MAX (T.ContractTypeId)
    FROM @t T
    GROUP BY
        T.PropertyId
) X ON X.PropertyId = T.PropertyId AND ISNULL(T.ContractTypeId,0) = ISNULL(X.ContractType,0)

输出

PropertyId  ContractType
160         Signed
165         Not Signed
170         Postponed

答案 1 :(得分:1)

您似乎想要:

select top (1) with ties propertyid, 
       (case when ContractType = 2 then 'Signed' 
             when ContractType = 1 then 'Postponed' 
             else 'Not singed'
        end) as ContractType 
from table t
order by row_number() over (partition by propertyid 
                               order by (case when ContractType = 2 then 0
                                              when ContractType = 1 then 1
                                              else 2
                                          end) 
                           );

答案 2 :(得分:1)

您可以使用CASE语句:https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql

SELECT
  PropertyId,
  "ContractType" = CASE ContactTypeID
    WHEN NULL THEN 'Not signed'
    WHEN 1 THEN 'Postponed'
    ELSE 'Signed'
  END

FROM
  YourTable

答案 3 :(得分:0)

尝试一下。假设您有两个名为“ YourPropertyTable”和“ YourContractTypeTable”的表

SELECT T1.PropertyId, C.ContractType
FROM YourPropertyTable T1
OUTER APPLY
(
   SELECT MAX(ISNULL(ContractTypeId,0)) Max_ContractTypeId
   FROM YourPropertyTable
   WHERE PropertyId = T1.PropertyId
) T2
LEFT JOIN YourContractTypeTable C ON C.ContractTypeId = T2.Max_ContractTypeId

答案 4 :(得分:0)

with states as
(select propertyId, max(ContractTypeId) as status
from contracts
group by propertyId)
select propertyId, 
   case 
        when status = 1 then 'Postponed'
        when status = 2 then 'Signed'       
        else 'Not signed'
   end as state
from states;