我在此表 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
答案 0 :(得分:1)
您可以在CASE
和COUNT
函数的帮助下使用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)
或者,您可以避免使用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)
答案 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