How Can I Order in an SQL Statement? - sql-server

I have these tables: Stock, Unit, Location, Category, StockBalance
At StockBalance: there is StockID from Stock, UnitId from Unit, LocationID from Location
I save at StockBalance Table like following
StockBalanceID | StockID | UnitID | LocationID | BalanceQuantity
1 | 1 | 1 | 1 | 20
2 | 1 | 2 | 1 | 30
3 | 1 | 3 | 1 | 40
4 | 2 | 1 | 2 | 20
5 | 2 | 2 | 2 | 30
6 | 2 | 3 | 2 | 40
I would like to show on Classic ASP as :
Group By : CategoryName
Stock Name Quantity Location Name
Qty | Unit | Qty | Unit | Qty | Unit
Stock One | 20 | One | 30 | Two | 40 | Three | Location One
Stock Two | 20 | One | 30 | Two | 40 | Three | Location Two
How can I Select From StockBalance to get like above? How about my edit one?
Please help me !

PIVOT is what you want.
First some sample data setup:
create table yourTable (
StockBalanceID int, StockID int, UnitID int, LocationID int, BalanceQuantity int);
insert yourTable
select 1 , 1 , 1 , 1 , 20
union all select 2 , 1 , 2 , 1 , 30
union all select 3 , 1 , 3 , 1 , 40
union all select 4 , 2 , 1 , 2 , 20
union all select 5 , 2 , 2 , 2 , 30
union all select 6 , 2 , 3 , 2 , 40
;
Now to do the work...
select StockID, LocationID,
sum(case UnitID when 1 then BalanceQuantity end) as [Unit One],
sum(case UnitID when 2 then BalanceQuantity end) as [Unit Two],
sum(case UnitID when 3 then BalanceQuantity end) as [Unit Three]
from yourTable
group by StockID, LocationID;

Try the following
DECLARE #StockBalances TABLE(
StockBalanceID INT,
StockID INT,
UnitID INT,
LocationID INT,
BalanceQuantity FLOAT
)
DECLARE #Stock TABLE(
StockID INT,
StockName VARCHAR(10)
)
DECLARE #Unit TABLE(
UnitID INT,
UnitName VARCHAR(10)
)
DECLARE #Location TABLE(
LocationID INT,
LocationName VARCHAR(10)
)
INSERT INTO #StockBalances SELECT 1,1,1,1,20
INSERT INTO #StockBalances SELECT 2,1,2,1,30
INSERT INTO #StockBalances SELECT 3,1,3,1,40
INSERT INTO #StockBalances SELECT 4,2,1,2,20
INSERT INTO #StockBalances SELECT 5,2,2,2 ,30
INSERT INTO #StockBalances SELECT 6,2,3,2,40
INSERT INTO #Stock SELECT 1, 'Stock 1'
INSERT INTO #Stock SELECT 2, 'Stock 2'
INSERT INTO #Unit SELECT 1, 'Unit 1'
INSERT INTO #Unit SELECT 2, 'Unit 2'
INSERT INTO #Unit SELECT 3, 'Unit 3'
INSERT INTO #Location SELECT 1, 'Location 1'
INSERT INTO #Location SELECT 2, 'Location 2'
SELECT *
FROM (
SELECT s.StockName,
sb.BalanceQuantity,
u.UnitName,
l.LocationName
FROM #StockBalances sb INNER JOIN
#Stock s ON sb.StockID = s.StockID INNER JOIN
#Unit u ON sb.UnitID = u.UnitID INNER JOIN
#Location l ON sb.LocationID = l.LocationID
) t
PIVOT (SUM(BalanceQuantity) FOR UnitName IN ([Unit 1], [Unit 2], [Unit 3])) p

Related

SQL query to find results with no gap in dates

I have a table with ClaimNumber, NoteCreateDate, NoteType
I wanted to find the claims that has notes like 'Review sent' back to back with no gap in the NoteCreateDate
eg.
+-------------+----------------+--------------------+----------+
| ClaimNumber | NoteCreateDate | Notes | NoteType |
+-------------+----------------+--------------------+----------+
| 12121 | 12/01/2017 | ReviewSent | Subject |
| 12121 | 12/05/2017 | PackagesenttoABC | Details |
| 12121 | 12/07/2017 | ReviewSent | Subject |
| 10005 | 05/06/2018 | ReviewSent | Subject |
| 10005 | 05/07/2018 | ReviewSent | Subject |
| 10005 | 05/08/2018 | ReviewSent | Subject |
| 10005 | 05/12/2018 | Fieldinvestigation | SIU |
+-------------+----------------+--------------------+----------+
Expected
From this example I wanted only the claim number 10005 since it the claim that has the notes 'Review Sent' back to back with no gap in the date(consecutive Dates). For instance, I wanted to find the claims that has the note with phrase 'ReviewSent' created today and the following note should also be the same 'Review sent', no matter when it was created, May be the next day or even 10 days later .. Thanks in Advance
My current MS SQL query.
select cm.ClaimNum, a.NoteCreateDate, a.Notes, a.NoteType
from CMaster cm
left join Note a on cm.ClaimNum = a.PARENTREF
left join NoteType] b on b.ID = a.TYPECODE
where Body like '%Review Sent%'
So if you want to find the ClaimNumber(s) where the ReviewSent notes are sent back-2-back then this query will get them
CREATE TABLE T1
([ClaimNumber] int, [NoteCreateDate] datetime, [Notes] varchar(18), [NoteType] varchar(7))
;
INSERT INTO T1
([ClaimNumber], [NoteCreateDate], [Notes], [NoteType])
VALUES
(12121, '2017-12-01 00:00:00', 'ReviewSent', 'Subject'),
(12121, '2017-12-05 00:00:00', 'PackagesenttoABC', 'Details'),
(12121, '2017-12-07 00:00:00', 'ReviewSent', 'Subject'),
(10005, '2018-05-06 00:00:00', 'ReviewSent', 'Subject'),
(10005, '2018-05-07 00:00:00', 'ReviewSent', 'Subject'),
(10005, '2018-05-08 00:00:00', 'ReviewSent', 'Subject'),
(10005, '2018-05-12 00:00:00', 'Fieldinvestigation', 'SIU')
;
SELECT DISTINCT X.ClaimNumber
FROM(
SELECT
ClaimNumber
,NoteCreateDate
,Notes
,NoteType
,LD=LEAD( Notes )OVER(PARTITION BY ClaimNumber ORDER BY NoteCreateDate ASC)
FROM dbo.T1
) X WHERE LD= 'ReviewSent' AND X.Notes= 'ReviewSent'
DROP TABLE dbo.T1
Result
ClaimNumber
10005
Select * into #tmp
from
(
Select 12121 as ClaimNumber,'12/01/2017' as
NoteCreateDate,'ReviewSent' as Notes,'Subject' as NoteType
union
Select 12121 , '12/05/2017' , 'PackagesenttoABC' , 'Details'
union
Select 12121 , '12/07/2017' , 'ReviewSent' ,
'Subject'
union
Select 10005 , '05/06/2018' , 'ReviewSent' , 'Subject'
union
Select 10005 , '05/07/2018' , 'ReviewSent' ,
'Subject'
union
Select 10005 , '05/08/2018' , 'ReviewSent' , 'Subject'
union
Select 10005 , '05/12/2018' , 'Fieldinvestigation' , 'SIU'
) t
/*create another temp table to simplify the query*/
Select * , ROW_NUMBER() OVER (PARTITION BY ClaimNumber ORDER BY
ClaimNumber)
as ClaimCounter into #tmp2 from #tmp
/** finally get the claimnos that have consecutive NoteCreate Date **/
SELECT distinct t1.ClaimNumber FROM #tmp2 t1
inner join #tmp2 t2 on (t1.ClaimCounter = t2.ClaimCounter - 1 and
t1.ClaimNumber = t2.ClaimNumber)
where
DATEDIFF(DAY,t1.NoteCreateDate,t2.NoteCreateDate) = 1
and
t1.Notes ='ReviewSent' and t2.Notes ='ReviewSent'

Extending a Pivot

I have a Documents table and an Events table.
Documents table has ID and a bunch of other fields not relevant to
this question.
Events table has DocID, EventType, EventDate, and UserID.
A document may have zero or more Events of any of these EventTypes:
0 = Created
1 = Modified
2 = Submitted
3 = Approved
DocID | EventType | EventDate | UserID
-----------------------------------------------
1 | 0 | 1-2-2017 | 123
1 | 1 | 1-3-2017 | 456
1 | 1 | 1-4-2017 | 489
1 | 2 | 1-5-2017 | 357
2 | 0 | 1-6-2017 | 951
2 | 1 | 1-7-2017 | 654
2 | 2 | 1-8-2017 | 654
2 | 3 | 1-9-2017 | 357
Pivoting the Events table is easy enough:
SELECT DocID, [0] AS CreatedDate, [1] AS ModifiedDate,
[2] AS SubmittedDate, [3] AS ApprovedDate
FROM (SELECT DocID, EventType, EventDate FROM Events
WHERE DocID IS NOT NULL AND EventDate IS NOT NULL) AS DocEvents
PIVOT (MAX(EventDate) FOR EventType IN ([0], [1], [2], [3]))
AS DocEventsPivot
For my purposes, the most recent event of a given type is wanted, thus the MAX aggregate:
DocID | CreatedDate | ModifiedDate | SubmittedDate | ApprovedDate
-----------------------------------------------------------------
1 | 1-2-2017 | 1-4-2017 | 1-5-2017 | NULL
2 | 1-6-2017 | 1-7-2017 | 1-8-2017 | 1-9-2017
How can I get the UserID translated to CreatedBy, ModifiedBy, SubmittedBy, and ApprovedBy to correspond to the dates of the appropriate EventType?
I will not know the possible values of UserID in advance.
Desired Output:
DocID | CreatedDate | ModifiedDate | SubmittedDate | ApprovedDate | CreatedBy | ModifiedBy | SubmittedBy | ApprovedBy
---------------------------------------------------------------------------------------------------------------------
1 | 1-2-2017 | 1-4-2017 | 1-5-2017 | NULL | 123 | 489 | 357 | NULL
2 | 1-6-2017 | 1-7-2017 | 1-8-2017 | 1-9-2017 | 951 | 654 | 654 | 657
Rather than using PIVOT another solution is using OUTER APPLY.
CREATE TABLE #Documents (ID int)
CREATE TABLE #Events (DocID int, EventType int, EventDate date, UserID int)
INSERT INTO #Documents VALUES
(1),
(2)
INSERT INTO #Events VALUES
(1, 0, '1-2-2017', 123),
(1, 1, '1-3-2017', 456),
(1, 1, '1-4-2017', 489),
(1, 2, '1-5-2017', 357),
(2, 0, '1-6-2017', 951),
(2, 1, '1-7-2017', 654),
(2, 2, '1-8-2017', 654),
(2, 3, '1-9-2017', 357)
SELECT
DOC.ID AS 'DocID',
CRT.EventDate AS 'CreatedDate',
MFY.EventDate AS 'ModifiedDate',
SUB.EventDate AS 'SubmittedDate',
APR.EventDate AS 'ApprovedDate',
CRT.UserID AS 'CreatedBy',
MFY.UserID AS 'ModifiedBy',
SUB.UserID AS 'SubmittedBy',
APR.UserID AS 'ApprovedBy'
FROM
#Documents AS DOC
OUTER APPLY (SELECT TOP 1 EventDate, UserID FROM #Events WHERE DocID = DOC.ID AND EventType = 0 ORDER BY EventDate DESC) AS CRT
OUTER APPLY (SELECT TOP 1 EventDate, UserID FROM #Events WHERE DocID = DOC.ID AND EventType = 1 ORDER BY EventDate DESC) AS MFY
OUTER APPLY (SELECT TOP 1 EventDate, UserID FROM #Events WHERE DocID = DOC.ID AND EventType = 2 ORDER BY EventDate DESC) AS SUB
OUTER APPLY (SELECT TOP 1 EventDate, UserID FROM #Events WHERE DocID = DOC.ID AND EventType = 3 ORDER BY EventDate DESC) AS APR
DROP TABLE #Documents
DROP TABLE #Events
Try the following
CREATE TABLE #Events (DocID int, EventType int, EventDate date, UserID int)
INSERT INTO #Events VALUES
(1, 0, '1-2-2017', 123),
(1, 1, '1-3-2017', 456),
(1, 1, '1-4-2017', 489),
(1, 2, '1-5-2017', 357),
(1, 2, '1-4-2017', 666),
(2, 0, '1-6-2017', 951),
(2, 1, '1-7-2017', 654),
(2, 2, '1-8-2017', 654),
(2, 3, '1-9-2017', 357)
SELECT
DocID,
MAX(CASE WHEN EventType=0 THEN EventDate END) [CreatedDate],
MAX(CASE WHEN EventType=1 THEN EventDate END) [ModifiedDate],
MAX(CASE WHEN EventType=2 THEN EventDate END) [SubmittedDate],
MAX(CASE WHEN EventType=3 THEN EventDate END) [ApprovedDate],
MAX(CASE WHEN EventType=0 THEN LastUserID END) [CreatedBy],
MAX(CASE WHEN EventType=1 THEN LastUserID END) [ModifiedBy],
MAX(CASE WHEN EventType=2 THEN LastUserID END) [SubmittedBy],
MAX(CASE WHEN EventType=3 THEN LastUserID END) [ApprovedBy]
FROM
(
SELECT
DocID,
EventDate,
EventType,
LAST_VALUE(UserID)OVER(
PARTITION BY DocID,EventType
ORDER BY EventDate
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) LastUserID
FROM #Events
) q
GROUP BY DocID
DROP TABLE #Events
Or you can use IFF instead CASE. I prefer use CASE because it isn't block ELSE
SELECT
DocID,
MAX(IIF(EventType=0,EventDate,NULL)) [CreatedDate],
MAX(IIF(EventType=1,EventDate,NULL)) [ModifiedDate],
MAX(IIF(EventType=2,EventDate,NULL)) [SubmittedDate],
MAX(IIF(EventType=3,EventDate,NULL)) [ApprovedDate],
MAX(IIF(EventType=0,LastUserID,NULL)) [CreatedBy],
MAX(IIF(EventType=1,LastUserID,NULL)) [ModifiedBy],
MAX(IIF(EventType=2,LastUserID,NULL)) [SubmittedBy],
MAX(IIF(EventType=3,LastUserID,NULL)) [ApprovedBy]
FROM
(
SELECT
DocID,
EventDate,
EventType,
LAST_VALUE(UserID)OVER(
PARTITION BY DocID,EventType
ORDER BY EventDate
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) LastUserID
FROM #Events
) q
GROUP BY DocID

Create the summary table SQL

I have a table of product stock (ProductStockTemp):
ProductStockId | ProductCode | ProductName | ProductStockClosingBalance
-------------------------------------------------------------------------
1 | A1 | A2 | 200
2 | B1 | B2 | 0
3 | A1 | A2 | 100
4 | C1 | C2 | -400
5 | B1 | B2 | 700
6 | C1 | C2 | 0
7 | D1 | D2 | 0
8 | D1 | D2 | 0
I would like to create a table like that
ProductCode | ProductName | TypeA | TypeB
------------------------------------------
A1 | A2 | 200 | 100
B1 | B2 | 0 | 700
C1 | C2 | -400 | 0
D1 | D2 | 0 | 0
It means the first product record will be the product type A and the latest record will be the product type B. I think i have to select the latest product record first. However, the problem arises when the product appears one time then it will choose this record. In this case, I want the product type B will be 0 since the first will be the product type A and the latest will be the type B. My query to select the latest product record in the table
select
p.ProductCode,
p.ProductName,
p.ProductStockClosingBalance
from
ProductStockTemp p
where
p.ProductStockId = (select MAX(q.ProductStockId)
from ProductStockTemp q
where p.ProductCode = q.ProductCode)
order by
p.ProductCode
I'm really stuck right now!
Most obvius in my opinion for this case:
;with cteStock as
(
select
p.ProductCode,
p.ProductName,
p.ProductStockClosingBalance,
row_number() over(partition by p.ProductCode, p.ProductName order by p.ProductStockId asc) rn_asc,
row_number() over(partition by p.ProductCode, p.ProductName order by p.ProductStockId desc) rn_desc,
from ProductStockTemp p
)
select
s.ProductCode, s.ProductName,
sum(case when s.rn_asc = 1 then s.ProductStockClosingBalance else 0) as TypeA,
sum(case when s.rn_desc = 1 and s.rn_asc != s.rn_desc then s.ProductStockClosingBalance else 0) as TypeB
from cteStock s
group by s.ProductCode, s.ProductName
but it's no good to have such a denormalized table with no info about period and names stored right here.
s.rn_asc != s.rn_desc - for the case when there is only one row.
Not sure about default zero but it's up to you and your task definition.
I suggest you to learn SQL GROUP BY Statement
SELECT ProductCode, ProductName, min(ProductStockClosingBalance) as TypeA, Max(ProductStockClosingBalance) as TypeB
FROM ProductStockTemp p
GROUP BY ProductCode, ProductName
This query does what you want.
declare #prod table(ProductStockId int, ProductCode varchar(10), ProductName varchar(10), ProductStockClosingBalance int)
insert #prod values
( 1 , 'A1' , 'A2' , 200),
( 2 , 'B1' , 'B2' , 0),
( 3 , 'A1' , 'A2' , 100),
( 4 , 'C1' , 'C2' , -400),
( 5 , 'B1' , 'B2' , 700),
( 6 , 'C1' , 'C2' , 0),
( 7 , 'D1' , 'D2' , 0),
( 8 , 'D1' , 'D2' , 0 )
;with prod as(
select *
,ROW_NUMBER() over(partition by productcode order by ProductStockId) rn1
,ROW_NUMBER() over(partition by productcode order by ProductStockId desc) rn2
from #prod
)
select productcode,ProductName,
(select ProductStockClosingBalance from prod p1 where p.productcode=p1.ProductCode and p1.rn1=1) TypeA,
ProductStockClosingBalance typeB
from prod p
where rn2=1
Results:
productcode ProductName TypeA typeB
A1 A2 200 100
B1 B2 0 700
C1 C2 -400 0
D1 D2 0 0
use below query
;With ctef as (select ProductCode , ProductName , ProductStockClosingBalance
row_number()over(partition by ProductCode , ProductName ordered by ProductStockId asc) as r from ProductStock)
, ctef1 as ( select * from ctef where r =1)
, ctel as (select ProductCode , ProductName , ProductStockClosingBalance
row_number()over(partition by ProductCode , ProductName ordered by ProductStockId desc)as r2 from ProductStock )
, ctel1 as ( select * from ctel where r =1)
select f.ProductCode , f.ProductName ,f.ProductStockClosingBalance as typea ,nullif(l.ProductStockClosingBalance ,f.ProductStockClosingBalance ) as typeB
from ctef1 f left join ctel1 s
on f.ProductCode =s.ProductCode and f.ProductName =s.ProductName
if using sql servere 2012 or above Analytic Functions FIRST_VALUE (Transact-SQL) and LAST_VALUE (Transact-SQL) can be used .

Rank consecutive null values

I want to rank consecutive null value for my records. Every record will be rank as 1. For the null value that only appear once, the rank will also be 1. But for the null values that appear in a consecutive way, the rank will be 1 for the first record and 2 for the second record and so on. Here's my code.
CREATE TABLE #my_table
(
id BIGINT IDENTITY PRIMARY KEY
,fruit varchar(100)
);
INSERT INTO #my_table
SELECT 'apple'
UNION ALL SELECT 'apple'
UNION ALL SELECT NULL
UNION ALL SELECT 'pineapple'
UNION ALL SELECT 'banana'
UNION ALL SELECT NULL
UNION ALL SELECT NULL
UNION ALL SELECT 'orange'
select * from #my_table
Intended result
+----+-----------+------+
| id | fruit | rank |
+----+-----------+------+
| 1 | apple | 1 |
| 2 | apple | 1 |
| 3 | NULL | 1 |
| 4 | pineapple | 1 |
| 5 | banana | 1 |
| 6 | NULL | 1 |
| 7 | NULL | 2 |
| 8 | orange | 1 |
+----+-----------+------+
How should I query it?
Please help!
You can use difference of ROW_NUMBER to get the grouping of consecutive NULL values:
WITH Cte AS(
SELECT *,
g = ROW_NUMBER() OVER(ORDER BY id)
- ROW_NUMBER() OVER(PARTITION BY fruit ORDER BY id)
FROM #my_table
)
SELECT
id,
fruit,
CASE
WHEN fruit IS NULL THEN ROW_NUMBER() OVER(PARTITION BY fruit, g ORDER BY id)
ELSE 1
END AS rank
FROM Cte
ORDER BY id;
ONLINE DEMO
CREATE TABLE #my_table
(
id BIGINT IDENTITY PRIMARY KEY
,fruit varchar(100)
);
INSERT INTO #my_table
SELECT 'apple'
UNION ALL SELECT 'apple'
UNION ALL SELECT NULL
UNION ALL SELECT 'pineapple'
UNION ALL SELECT 'banana'
UNION ALL SELECT NULL
UNION ALL SELECT NULL
UNION ALL SELECT 'orange'
;
WITH REC_CTE (id,fruit,ranks)
AS (
-- Anchor definition
SELECT id,
fruit,
1 as ranks
FROM #my_table
WHERE fruit is not null
-- Recursive definition
UNION ALL
SELECT son.id,
son.fruit,
case when son.fruit is null AND father.fruit is null then
father.ranks + 1
else
1
end as ranks
FROM #my_table son INNER JOIN
REC_CTE father
on son.id = father.id +1
WHERE son.fruit is null
--AND father.fruit is null
)
SELECT * from REC_CTE order by id
DROP TABLE #my_table
Following solution doesn't use recursion (limited to 32767 level = ~ rows depending on solution) and also it uses only two agregate/ranking functions (SUM and DENSE_RANK):
;WITH Base
AS (
SELECT *, IIF(fruit IS NULL, SUM(IIF(fruit IS NOT NULL, 1, 0)) OVER(ORDER BY id), NULL) AS group_num
FROM #my_table t
)
SELECT *, IIF(fruit IS NULL, DENSE_RANK() OVER(PARTITION BY group_num ORDER BY id), 1) rnk
FROM Base b
ORDER BY id
Results:
id fruit group_num rnk
--- --------- --------- ---
100 apple NULL 1
125 apple NULL 1
150 NULL 2 1
175 pineapple NULL 1
200 banana NULL 1
225 NULL 4 1
250 NULL 4 2
275 orange NULL 1
300 NULL 5 1
325 NULL 5 2
350 NULL 5 3

TSQL UNION GETTING UNIQUE VALUE

I'm trying to get the unique record between two databases based on two criteria. The criteria is:
If the data is found in database 1 (#SCCM in my example below), it
is given preference
Grab the MAX resource id within the selected database
Here is an example, which is half working. The database preference is working, but the maximum resource id WITHIN that database isn't. Right now it's selecting the max between both #SMS and #SCCM
DECLARE #SMS TABLE (
name0 varchar(100),
resid int
)
DECLARE #SCCM TABLE (
name0 varchar(100),
resid int
)
INSERT INTO #SMS
SELECT 'TEST', 1000 UNION
SELECT 'TEST', 1500 UNION
SELECT 'TEST1', 2000 UNION
SELECT 'TEST2', 3000 UNION
SELECT 'TEST3', 4000
INSERT INTO #SCCM
SELECT 'TEST', 100 UNION
SELECT 'TEST', 150 UNION
SELECT 'TEST1', 200 UNION
SELECT 'TEST2', 300
SELECT MIN(SMSDB) as SMSDB, MAX(Resid), Name0 FROM
(
SELECT name0, resid, 2 as SMSDB FROM #SMS
UNION ALL
SELECT name0, resid, 1 as SMSDB FROM #SCCM
) as tbl
GROUP BY NAME0
Expected results:
SMSDB | Resid | Name0
----------------------
1 | 150 | TEST
1 | 200 | TEST1
1 | 300 | TEST2
2 | 4000 | TEST3
You can use partitions:
;WITH tbl as
(
SELECT name0, resid, 2 as SMSDB FROM SMS
UNION ALL
SELECT name0, resid, 1 as SMSDB FROM SCCM
),
t as (
SELECT *,
ROW_NUMBER()
over (partition By name0 order by SMSDB, resid desc )
as rn
FROM tbl
)
SELECT * FROM t
WHERE rn = 1
Results:
| NAME0 | RESID | SMSDB | RN |
------------------------------
| TEST | 150 | 1 | 1 |
| TEST1 | 200 | 1 | 1 |
| TEST2 | 300 | 1 | 1 |
| TEST3 | 4000 | 2 | 1
The partition solution may in fact be better, but it hurts my brain. What about just excluding the values in SMS if they exist in SCCM?
SELECT MIN(SMSDB) as SMSDB, MAX(Resid), Name0 FROM
(
SELECT name0, resid, 2 as SMSDB FROM #SMS SMS
WHERE NOT EXISTS (SELECT * FROM #SCCM WHERE name0 = SMS.name0)
UNION ALL
SELECT name0, resid, 1 as SMSDB FROM #SCCM
) as tbl
GROUP BY NAME0
or even
SELECT 1 as SMSDB, MAX(resid), name0 FROM #SCCM
GROUP BY name0
UNION ALL
SELECT 2 as SMSDB, MAX(resid), name0 FROM #SMS SMS
WHERE NOT EXISTS (SELECT * FROM #SCCM WHERE name0 = SMS.name0)
GROUP BY name0
ORDER BY name0

Resources