Friday, September 28, 2012

UNIONs in SQL

This had the following which makes UNIONs look super simple:

SELECT SUM([Customers]) as [# of Cust]
FROM (
SELECT COUNT(*) AS [Customers]
FROM Customers
WHERE (active = 1)
and (RepID = 4)
union
SELECT COUNT(*) AS [Customers]
FROM Customers
WHERE (active = 1)
and (RepID = 4)
) as aPlus

 
 

Note: ORDER BY must come after both SELECTs to apply to both and should reference columns numerically by column number in from the left on a table.

No comments:

Post a Comment