使用SQL将记录与某些规则合并

时间:2012-10-25 22:07:32

标签: sql merge duplicates concatenation

我有一张包含4条记录的表格:

NAME    INSTRUMENT    BOOLEAN 1  BOOLEAN 2
Bob     Organ         TRUE       FALSE
Thomas  Violin        FALSE      FALSE
Bob     Piano         FALSE      TRUE

我想将记录与相同的“NAME”合并,以获得:

Bob     Organ Piano   TRUE       TRUE
Thomas  Violin        FALSE      FALSE

合并时我想要的规则是什么?

  • “文字字段”只是连接在一起(例如:风琴+钢琴==>“管风琴”)

  • “boolean fields”与LOGICAL OR合并(例如:TRUE或FALSE = TRUE)

我的问题:

1)我将选择使用哪种软件来执行此操作!带有SQL查询的数据库(SQLite,MySQL甚至Access)还是Excel?

2)如果最佳解决方案是数据库,那么SQL查询是做什么的?

提前多多感谢!

2 个答案:

答案 0 :(得分:2)

我的选择和SQLServer2005 +

SELECT a.NAME AS NAME,(
SELECT ISNULL(b.INSTRUMENT, '')+ ' '
FROM dbo.COExample b WHERE b.NAME=a.NAME
FOR XML PATH('')) AS INSTRUMENT, MAX(CAST(BOOLEAN1 AS int)) AS BOOLEAN1, MAX(CAST(BOOLEAN2 AS int)) AS BOOLEAN2
FROM dbo.COExample a
GROUP BY a.NAME

SQLFiddle

上的示例

答案 1 :(得分:1)

使用SQL Server 2005或更高版本,下面是一组T-SQL语句,它们将说明上面的示例(使用交叉应用和案例语句的combox):

CREATE TABLE [dbo].[COExample](
   [NAME] [varchar](50) NULL,
   [INSTRUMENT] [varchar](50) NULL,
   [BOOLEAN1] [bit] NULL,
   [BOOLEAN2] [bit] NULL
);

INSERT INTO dbo.COExample VALUES('Bob','Organ',1,0);
INSERT INTO dbo.COExample VALUES('Thomas','Violin',0,0);
INSERT INTO dbo.COExample VALUES('Bob','Piano',0,1);

SELECT DISTINCT c.NAME, RTRIM(CombInstruments.combinstruments) AS 'INSTRUMENTS'
,CASE WHEN EXISTS(SELECT * FROM dbo.COExample b1 WHERE b1.NAME = c.NAME AND b1.BOOLEAN1 = 1) THEN 1 ELSE 0 END AS 'BOOLEAN1'
,CASE WHEN EXISTS(SELECT * FROM dbo.COExample b2 WHERE b2.NAME = c.NAME AND b2.BOOLEAN2 = 1) THEN 1 ELSE 0 END AS 'BOOLEAN2'
FROM dbo.COExample c

CROSS APPLY
(
   SELECT ISNULL(c2.INSTRUMENT,'') + ' '
   FROM dbo.COExample c2
   WHERE c2.NAME = c.NAME
   ORDER BY c2.INSTRUMENT FOR XML PATH('')
) CombInstruments(combinstruments)