【发布时间】:2016-07-08 16:04:48
【问题描述】:
我有三个不同的表,月份和项目如下: 表1
month books
April-2016 2
February-2016 7
January-2016 1
June-2016 6
May-2016 1
September-2015 1
表2
month copies
April-2016 92
August-2015 1
February-2016 49
January-2016 5
June-2016 127
表3
month pens
February-2016 74
January-2016 1
June-2016 66
March-2016 136
May-2016 128
现在,我看起来像这样: 月书副本笔 - 月份列应合并,其他数据应放在相应列中(如果没有可用数据,则应放置 0),例如
month books copies pens
April-2016 2 92 0
September-2015 1 0 0
August-2015 0 1 0
June-2016 6 127 66
我试过了
select COALESCE(t1.Month,t2.Month,t3.Month) AS [Month],
ISNULL(t1.books,0) AS books,
ISNULL(tp.copies,0) AS copies,
ISNULL(tn.pens,0) AS pens
from #table1 t1
full join #table t2 on t1.month=t2.month
full join #table t3 on t1.month=t3.month
---Union 不起作用,因为它给了我 6 列(3 个月,我只需要 1)
【问题讨论】:
-
您的查询有什么问题?
-
您的查询正在从同一个表中提取数据 3 次。我不认为那是你的意思。老实说,您在获取数据时遇到此类问题的原因是您的设计存在缺陷。您不应该为每种类型的项目都有一个表格。您应该有一列表明它是哪种类型的项目。
-
@Sean Lange - 我希望目的是将结果插入新表中......
-
是的,它不是从 3 个临时表中的各个表中提取的数据,以便在报告中如此(这里与表设计无关......)
-
您的设计使这变得困难。如果您有更好的设计,查询会很简单。
标签: sql sql-server join union coalesce