SQL Select - 合并具有匹配ID的行

时间:2012-02-02 11:46:23

标签: sql

我有一张包含交易细节的表,

我已经设法在分类交易

方面回到原始数据形式

我现在需要做的是每次交易返回1行。

我目前拥有的是:

TransID | Type
1       | G
2       | G
2       | G
2       | G
3       | S
4       | G
4       | S
5       | X
5       | G
6       | G
6       | S
6       | X

每笔交易我需要的是返回以下内容:

TransID | Type
1       | G
2       | G
3       | S
4       | M
5       | G
6       | M

所以,我需要的是,如果一个事务是一行,那么返回那个Type。

如果某个事务有多行,请按以下方式进行评估:

 All Types = G -> Return G
 All Types = S -> Return S
 Mix of Types G and S -> Return M
 Mix of Types G and X -> Return G
 Mix of Types S and X -> Return S
 Mix of Types S, G and X -> Return M

2 个答案:

答案 0 :(得分:4)

一种简单的方法可能是......

SELECT
  TransID,
  CASE
    WHEN G+S+X = 3 THEN 'M'
    WHEN S+X   = 2 THEN 'S'
    WHEN G+X   = 2 THEN 'G'
    WHEN G+S   = 2 THEN 'M'
    WHEN S     = 1 THEN 'S'
    WHEN G     = 1 THEN 'G'
                   ELSE '-'
  END as aggregate_type
FROM
(
  SELECT
    TansID,
    MAX(CASE WHEN Type = 'G' THEN 1 ELSE 0 END)   AS G,
    MAX(CASE WHEN Type = 'S' THEN 1 ELSE 0 END)   AS S,
    MAX(CASE WHEN Type = 'X' THEN 1 ELSE 0 END)   AS X
  FROM
    YourTable
  GROUP BY
    TransID
)
  AS data

虽然您可以将CASE语句合并为短,但在必要时应该很容易更改。

答案 1 :(得分:0)

你走了:

CREATE FUNCTION dbo.GetFinalType (@g int, @s int, @x int)
RETURNS CHAR(1)
AS
begin

IF @g>0 AND @s=0 AND @x=0 RETURN 'G'
IF @g=0 AND @s>0 AND @x=0 RETURN 'S'
IF @g>0 AND @s>0 AND @x=0 RETURN 'M'
IF @g>0 AND @s=0 AND @x>0 RETURN 'G'
IF @g=0 AND @s>0 AND @x>0 RETURN 'S'
IF @g>0 AND @s>0 AND @x>0 RETURN 'M'

RETURN '?'
END

并查询:

SELECT 
    TransId, 
    dbo.GetFinalType(
        SUM(CASE WHEN Type='G' THEN 1 ELSE 0 END),
        SUM(CASE WHEN Type='S' THEN 1 ELSE 0 END),
        SUM(CASE WHEN Type='X' THEN 1 ELSE 0 END)) FinalType
FROM
    Transactions
GROUP BY 
    TransId