在另一列中具有不同值的Id列需要显示具有specilal值

时间:2016-02-05 05:50:17

标签: mysql sql sql-server sql-server-2008

我在此表 Id 列中有一个表格测试, FuelId FuelDesc 列在那里。值类似于下表,基于我需要创建如下表所示的前三列,请帮助我获取。

ID   FuelID   FuelDesc 
100   01       Elec     
101   02       Gas      
102   02       Gas      
100   02       Gas     
101   01       Elec    
103   01       Elec     

O / P: -

ID    Pamenttype       
100   Both        
101   Both       
102   Gas         
103   Elec

4 个答案:

答案 0 :(得分:1)

您可以在CASECOUNT函数的帮助下使用MAX表达式:

SELECT
    ID,
    PaymentType = CASE WHEN COUNT(FuelId) > 1 THEN 'Both' ELSE MAX(FuelDESC) END
FROM test
GROUP BY ID

答案 1 :(得分:0)

SELECT ID, CASE WHEN rowCount = 1 THEN FuelDesc ELSE 'Both' END AS Pamenttype
FROM
(SELECT ID, MAX(FuelDesc) AS FuelDesc, COUNT(*) AS rowCount
 FROM mytable
 GROUP BY ID)

答案 2 :(得分:0)

您可以将Both定义为包含FuelID = '01'的一条记录和另一条FuelID = '02'的记录。假设{ID,FuelID}在表Test中是唯一的:

with BothPaymentTypes as (
    select t1.ID
    from Test t1
    join Test t2 on t1.ID = t2.ID
    where t1.FuelID = '01'
    and t2.FuelID = '02'
)
select ID, 'Both' as Pamenttype
from BothPaymentTypes
union all
select ID, FuelDesc
from Test
where ID not in (select ID from BothPaymentTypes)

[SQL Fiddle Demo]

或者,您可以避免使用COUNT和HAVING子句进行自联接 - 再次假设{ID,FuelID}是唯一的:

with BothPaymentTypes as (
    select ID
    from Test
    group by ID
    having count(*) = 2
)
select ID, 'Both' as Pamenttype
from BothPaymentTypes
union all
select ID, FuelDesc
from Test
where ID not in (select ID from BothPaymentTypes)

[SQL Fiddle Demo]

答案 3 :(得分:0)

WITH fuelCount
AS
(
    SELECT ID, COUNT(FuelID) AS fuelCount 
    FROM Test GROUP BY ID
)
SELECT fc.ID, 
CASE 
    WHEN fc.fuelCount > 1 THEN 'BOTH'
    ELSE (SELECT t.FuelDesc FROM Test t WHERE t.ID = fc.ID)
END AS Pamenttype
FROM fuelCount fc