在SQL Server中组合具有相同列的表

时间:2016-08-01 14:25:35

标签: sql sql-server union sql-server-2016

我正在尝试在SQL Server中组合两个具有相同列的表。

单独地,我的查询工作正常:

Select 
    _NAME, COUNT(_NAME) as Occurrences
From 
    SP6815_NOK
Where 
    _VALUE = 1
Group By 
    _NAME 
Order By 
    Occurrences desc

Select 
    _NAME, COUNT(_NAME) as Occurrences
From 
    SP6814_NOK
Where 
    _VALUE = 1
Group By 
    _NAME
Order By 
    Occurrences desc

导致:

Occurrences for SP6815_NOK

Occurrences for SP6814_NOK

我需要查询来执行我个人查询中列出的确切过滤器,但每次我尝试加入'条款或简单地列出'来自'声明,我得到一个模糊的列错误。

我认为这可能是因为某些消息或" _NAMES"由两个表共享,但我仍然需要它来计算出现次数而不是覆盖它们。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

如果您需要分隔行中的结果,请使用union

Select _NAME,COUNT(_NAME) as Occurrences
From SP6815_NOK 
Where _VALUE = 1
Group By _NAME 
union
Select _NAME,COUNT(_NAME)
From SP6814_NOK
Where _VALUE = 1
Group By _NAME
Order By Occurrences desc

如果您想要所有行(也是重复的),如果您想要不同的行

,则使用union all

否则如果yoe希望结果在同一行上,则使用完全限定名称

Select SP6815_NOK._NAME,COUNT(SP6815_NOK._NAME)   as Occurrences,  SP6814_NOK._NAME,COUNT(SP6814_NOK._NAME) as Occurrences2
From SP6815_NOK 
INNER JOIN SP6814_NOK ON SP6815_NOK._VALUE = SP6814_NOK._VALUE
Where _VALUE = 1
Group By SP6815_NOK._NAME,  SP6814_NOK._NAME
Order By Occurrences desc

答案 1 :(得分:1)

简单的UNION ALL不会按照您似乎需要的方式返回行。

试试这个:

编辑:不需要子选择

我的第一次尝试是复杂的。我不知道SQL Server允许在ORDER BY中使用哪个版本的列别名。如果这个更简单的版本不适合您并且您使用的是旧版本的SQL Server,那么您可以查看编辑历史记录并查找以前的代码...

Select 'SP6815_NOK' AS SourceTable
        ,NAME
        ,COUNT(_NAME) as Occurrences
From SP6815_NOK 
Where _VALUE = 1
Group By _NAME 

UNION ALL

Select 'SP6814_NOK' AS SourceTable
        ,NAME
        ,COUNT(_NAME) as Occurrences
From SP6814_NOK 
Where _VALUE = 1
Group By _NAME 

ORDER BY SourceTable,Occurrences

UPDATE:ORDER BY中的列别名......

看来,这是possible already in SQL Server 2005...,但不是WHERE ......我错过了某种方式:-)