我想根据某些条件将同一表中的两行或更多行合并得到结果。
在这里,我想将具有相同贸易头的行合并为单行。而我们忽略了预期结果合并格式中的面试位置(下图)。结果表的列数将取决于采访位置。
合并表中的说明 在这里,仅因焊工贸易的九列就有三个面试地点。并且每个位置选择计数最终都将合并。
我找到了Using Case之类的解决方案,但就我而言,贸易头,面试地点中的数据是不固定的。也许明天可以根据需要安装ASP.Net编程器或软件测试器。
答案 0 :(得分:1)
此以下脚本最多可使用3行。对于更多行,您需要在每个交易头的查询中添加更多逻辑。但是,由于不存在ID列来确定同一交易头之间的较旧和较新的行,因此将值放在9个不同的列上,但SelCnt列和值的顺序将不同步。但是,如果表中有ID或任何自动递增列,则所有内容都将像超级按钮一样工作。
您可以查看LIVE Demo Here
WITH CTE([Trade Head], [Select Count On Date 1], [Select Count On Date 2], [Select Count On Date 3],C1,C2,C3)
AS
(
SELECT [Trade Head], [Select Count On Date 1], [Select Count On Date 2],[Select Count On Date 3],
CASE WHEN RN = 1 THEN RN+0 WHEN RN = 2 THEN RN+2 WHEN RN = 3 THEN RN+4 END C1,
CASE WHEN RN = 1 THEN RN+1 WHEN RN = 2 THEN RN+3 WHEN RN = 3 THEN RN+5 END C2,
CASE WHEN RN = 1 THEN RN+2 WHEN RN = 2 THEN RN+4 WHEN RN = 3 THEN RN+6 END C3
FROM
(
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY [Trade Head]
ORDER BY [ID]
-- use ORDER BY [Trade Head] if no ID column exists
) RN
FROM your_table
) A
)
SELECT [Trade Head],
SUM(CASE WHEN C1 = 1 THEN [Select Count On Date 1] ELSE NULL END) SelCnt1,
SUM(CASE WHEN C2 = 2 THEN [Select Count On Date 2] ELSE NULL END) SelCnt2,
SUM(CASE WHEN C3 = 3 THEN [Select Count On Date 3] ELSE NULL END) SelCnt3,
SUM(CASE WHEN C1 = 4 THEN [Select Count On Date 1] ELSE NULL END) SelCnt4,
SUM(CASE WHEN C2 = 5 THEN [Select Count On Date 2] ELSE NULL END) SelCnt5,
SUM(CASE WHEN C3 = 6 THEN [Select Count On Date 3] ELSE NULL END) SelCnt6,
SUM(CASE WHEN C1 = 7 THEN [Select Count On Date 1] ELSE NULL END) SelCnt7,
SUM(CASE WHEN C2 = 8 THEN [Select Count On Date 2] ELSE NULL END) SelCnt8,
SUM(CASE WHEN C3 = 9 THEN [Select Count On Date 3] ELSE NULL END) SelCnt9
FROM CTE
GROUP BY [Trade Head]
答案 1 :(得分:0)
使用聚合
select Thead,max(Selcnt1),max(selcnt2),....max(selcnN) from table
group by Thead