我正在尝试创建一个包含组装号和每个组件的单行。
我有一个名为Assembly
的表,具有唯一标识符,该标识符可以绑定到inv_mast
表,并且该表中的组件可以绑定到相同的inv_mast
表。它还包括一个序列号。
inv_mast_uid | sequence_number | component_inv_mast_uid
453061 | 1 | 453024
453061 | 2 | 453017
453061 | 3 | 453020
453062 | 1 | 453019
453062 | 2 | 453027
(我的某些条目中只有2个组件)
我想要实现的是:
inv_mast_uid | component_inv_mast_uid_1 | component_inv_mast_uid_2 | component_inv_mast_uid_3
453061 | 453024 | 453017 | 453020
453062 | 453019 | 453027 | Null
我当时以为我会使用“ For Each”循环,但是我和SQL Server从来没有碰运气
答案 0 :(得分:6)
您尝试做的事情称为Pivot,希望对您有帮助
func main() {
m := getMap()
// Create a heap from the map and print the top N values.
h := getHeap(m)
for i := 1; i <= 3; i++ {
fmt.Printf("%d) %#v\n", i, heap.Pop(h))
}
// 1) main.kv{Key:"k11", Value:76}
// 2) main.kv{Key:"k2", Value:31}
// 3) main.kv{Key:"k5", Value:31}
}
func getHeap(m map[string]int) *KVHeap {
h := &KVHeap{}
heap.Init(h)
for k, v := range m {
heap.Push(h, kv{k, v})
}
return h
}
// See https://golang.org/pkg/container/heap/
type KVHeap []kv
// Note that "Less" is greater-than here so we can pop *larger* items.
func (h KVHeap) Less(i, j int) bool { return h[i].Value > h[j].Value }
func (h KVHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h KVHeap) Len() int { return len(h) }
func (h *KVHeap) Push(x interface{}) {
*h = append(*h, x.(kv))
}
func (h *KVHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
如果要查看Microsoft文档。 Pivot Table in Sql Server
问候
答案 1 :(得分:0)
假设您有最多三个组件,则可以使用这样的条件聚合。如果您拥有动态数量的组件,我们仍然可以使用条件聚合,但是需要更多的圈来容纳动态数量的列。
declare @Assembly table
(
inv_mast_uid int
, sequence_number int
, component_inv_mast_uid int
)
insert @Assembly values
(453061, 1, 453024)
, (453061, 2, 453017)
, (453061, 3, 453020)
, (453062, 1, 453019)
, (453062, 2, 453027)
select inv_mast_uid
, component_inv_mast_uid_1 = max(case when sequence_number = 1 then component_inv_mast_uid end)
, component_inv_mast_uid_2 = max(case when sequence_number = 2 then component_inv_mast_uid end)
, component_inv_mast_uid_3 = max(case when sequence_number = 3 then component_inv_mast_uid end)
from @Assembly
group by inv_mast_uid
order by inv_mast_uid
答案 2 :(得分:0)
如果可以确定列的最大值,则类似的事情应该起作用
select (select A.component_inv_mast_uid
from Assembly where inv_mast_uuid = A.inv_mast_uuid and sequence_number = 1) as component_inv_mast_uid_1,
(select A.component_inv_mast_uid
from Assembly where inv_mast_uuid = A.inv_mast_uuid and sequence_number = 2) as component_inv_mast_uid_2,
(select A.component_inv_mast_uid
from Assembly where inv_mast_uuid = A.inv_mast_uuid and sequence_number = 3) as component_inv_mast_uid_3
from (select distinct inv_mast_uid from Assembly) A
还可以通过动态请求构建来增强它。