0

I am trying to combine two tables with same columns in SQL Server.

Individually, my queries work fine:

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

and

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

Resulting in:

Occurrences for SP6815_NOK

and

Occurrences for SP6814_NOK

I need the query to perform the exact filters as listed in my individual queries but every time I try a 'join' clause or simply listing both tables under the 'from' statement, I get an ambiguous column error.

I think it might be because some of the messages or "_NAMES" are shared by both tables, but I still need it to count up the occurrences and not overwrite them. Could anyone help?

Shnugo
  • 66,100
  • 9
  • 53
  • 114
B. Heinrich
  • 31
  • 1
  • 1

2 Answers2

3

If you need the result in separated row then use 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

Use union all if you want all the rows (also duplicated) use only union if you want distinct rows

otherwise if yoe want the result on the same row use fully qualified name

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
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
1

A simple UNION ALL will not return the rows sorted the way you seem to need it.

Try this:

EDIT: no sub-selects needed

My first attempt was to complicated. I do not know with which version SQL Server allows to use column aliases in ORDER BY. If this simpler version does not work for you and you are using an older version of SQL Server, you might have a look in the edit history and find the previous code...

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: column-alias in ORDER BY...

It seems, that this was possible already in SQL Server 2005..., but not in WHERE... I've missed that somehow :-)

Shnugo
  • 66,100
  • 9
  • 53
  • 114