我有一张如下表格
RefNo | Amount | ID | Billed
1 20 1 1
1 20 2 1
2 10 3 0
2 10 4 0
2 10 5 0
3 30 6 1
3 30 7 0
3 30 8 1
3 30 9 0
我想要像下面的那样
RefNo | Amount | ID | Billed | Status
1 20 1 1 SingleBilled
1 20 2 1 SingleBilled
2 10 3 0 SingleUnBilled
2 10 4 0 SingleUnBilled
2 10 5 0 SingleUnBilled
3 30 6 1 MultipleBilled
3 30 7 0 MultipleBilled
3 30 8 1 MultipleBilled
3 30 9 0 MultipleBilled
此处状态需要基于refNo,Billed Flag 请帮帮我
答案 0 :(得分:1)
根据您目前为止提供的信息,这些内容有所帮助......请参阅小提琴:http://sqlfiddle.com/#!3/156c1/8
SELECT a.RefNo, a.Amount, a.ID, a.Billed,
CASE
WHEN b.Bill_Total = 0 THEN 'SingleUnBilled'
WHEN b.Bill_Count > b.Bill_Total THEN 'MultipleBilled'
WHEN b.Bill_Count = b.Bill_Total THEN 'SingleBilled'
ELSE ''
END AS [Status]
FROM test a
INNER JOIN
(
SELECT RefNo,
COUNT(Billed) AS Bill_Count,
SUM(CAST(Billed AS INT)) AS Bill_Total
FROM test
GROUP BY RefNo
) b
ON a.RefNo = b.RefNo