我们假设我们在DB中有以下表格:
CREATE TABLE #nodes(reporter varchar(10), groupname varchar(10), node varchar(20))
CREATE TABLE #nodes_extract(id int IDENTITY, min_node varchar(20), count_nodes int, descr varchar(10) );
CREATE TABLE #nodes_histo(reporter varchar(10), groupname varchar(10), node varchar(20), nodes_extract_id int)
数据示例:
INSERT INTO #nodes (reporter, groupname, node) VALUES ('rep1','group1','node1')
INSERT INTO #nodes (reporter, groupname, node) VALUES ('rep1','group1','node2')
INSERT INTO #nodes (reporter, groupname, node) VALUES ('rep1','group2','node3')
INSERT INTO #nodes (reporter, groupname, node) VALUES ('rep2','group1','node1')
INSERT INTO #nodes (reporter, groupname, node) VALUES ('rep2','group1','node4')
INSERT INTO #nodes (reporter, groupname, node) VALUES ('rep2','group2','node5')
INSERT INTO #nodes (reporter, groupname, node) VALUES ('rep3','group1','node5')
INSERT INTO #nodes (reporter, groupname, node) VALUES ('rep3','group1','node6')
INSERT INTO #nodes (reporter, groupname, node) VALUES ('rep3','group2','node7')
让我们将一些数据提取到#nodes_extract
中INSERT INTO #nodes_extract
SELECT min(node), count(node), 'blabla'
FROM #nodes
GROUP BY reporter, groupname
现在我想将#nodes中的所有信息插入#nodes_histo并添加nodes_extract_id #nodes_histo中的预期结果:
reporter groupname node nodes_extract_id rep1 group1 node1 1 rep1 group1 node2 1 rep1 group2 node3 4 rep2 group1 node1 2 rep2 group1 node4 2 rep2 group2 node5 5 rep3 group1 node5 3 rep3 group1 node6 3 rep3 group2 node7 6
你将如何实现目标? 是否可以不改变表格结构?
非常感谢! KAFE
答案 0 :(得分:1)
嗯,我觉得我找到了办法..
首先,在insert命令中需要DISTINCT
:
INSERT INTO #nodes_extract
SELECT DISTINCT min(node), count(node), 'blabla'
FROM #nodes
GROUP BY reporter, groupname
通过以下选择,我可以提取我正在寻找的信息:
INSERT INTO #nodes_histo
SELECT a.reporter, a.groupname,a.node, e.id
FROM
(SELECT reporter
, groupname
, node
, min(node) OVER (PARTITION BY REPORTER, groupname) m
, count(node) OVER (PARTITION BY REPORTER, groupname) c
FROM #nodes) a
LEFT JOIN
#nodes_extract e
ON a.m = e.min_node
AND a.c = e.count_nodes
答案 1 :(得分:0)
不,您可能需要包含一种加入表的方法,可能是在#nodes_extract中包含reporter和groupname。即使您尝试使用相同的查询(以及其他列)重新生成#nodes_extract,也无法保证订单是相同的。