how to store sql results into variable in sql server 2008 - sql

I have stored procedure and inside i have select statement, insert and update but in my select statement i would like the results to be stored in a variable so i can access it later on in my update statement. How can i store the result first in a variable? Here is my select statement:
SELECT
REV1 = COUNT(CASE WHEN QTR = 1 AND MAIN_SAT =1 AND ACTIVE_FLAG = 1 THEN 1 END),
REV2= COUNT(CASE WHEN QTR = 1 AND MAIN_EKL =1 AND ACTIVE_FLAG = 1 THEN 1 END),
REV3= COUNT(CASE WHEN QTR = 1 AND MAIN_LAM =1 AND ACTIVE_FLAG = 1 THEN 1 END),
REV4= COUNT(CASE WHEN QTR = 1 AND MAIN_JAC =1 AND ACTIVE_FLAG = 1 THEN 1 END)
FROM MyTable
The result of this select statement looks like this:
REV1 REV2 REV3 REV4
12 45 87 54

You can either make a table variable or individual variables (depending on your preference). Example with separate variables:
DECLARE #Rev1 int
DECLARE #Rev2 int
DECLARE #Rev3 int
DECLARE #Rev4 int
SELECT
#Rev1 = COUNT(CASE WHEN QTR = 1 AND MAIN_SAT =1 AND ACTIVE_FLAG = 1 THEN 1 END),
#Rev2= COUNT(CASE WHEN QTR = 1 AND MAIN_EKL =1 AND ACTIVE_FLAG = 1 THEN 1 END),
#Rev3= COUNT(CASE WHEN QTR = 1 AND MAIN_LAM =1 AND ACTIVE_FLAG = 1 THEN 1 END),
#Rev4= COUNT(CASE WHEN QTR = 1 AND MAIN_JAC =1 AND ACTIVE_FLAG = 1 THEN 1 END)
FROM MyTable

Try This
this will reduced the condition and much clearer.
DECLARE #Rev1 int
DECLARE #Rev2 int
DECLARE #Rev3 int
DECLARE #Rev4 int
SELECT
#Rev1 = SUM(CASE WHEN MAIN_SAT =1 THEN 1 ELSE 0 END),
#Rev2= SUM(CASE WHEN MAIN_EKL =1 THEN 1 ELSE 0 END),
#Rev3= SUM(CASE WHEN MAIN_LAM =1 THEN 1 ELSE 0 END),
#Rev4= SUM(CASE WHEN MAIN_JAC =1THEN 1 ELSE 0 END)
FROM MyTable
WHERE QTR = 1
AND ACTIVE_FLAG = 1

Related

Query to get a output in desired format

Proc type add sub multi div
1 A 1 0 1 1
1 B 2 2 0 1
Output should be in the format
Proc Aadd Asub Amulti Adiv Badd Bsub Bmulti Bdiv
1 1 0 1 1 2 2 0 1
A simple conditional aggregation should do the trick
Select Proc
,Aadd = max( case when type='A' then add else 0 end)
,Asub = max( case when type='A' then sub else 0 end)
,Amuti = max( case when type='A' then multi else 0 end)
,Adiv = max( case when type='A' then div else 0 end)
,Badd = max( case when type='B' then add else 0 end)
,Bsub = max( case when type='B' then sub else 0 end)
,Bmuti = max( case when type='B' then multi else 0 end)
,Bdiv = max( case when type='B' then div else 0 end)
From YourTable
Group By Proc
Another approach using CTE and Joins.
declare #table table(Proce int, type char(1), addi int, sub int, multi int, div int)
insert into #table values
(1,'A', 1, 0, 1, 1),
(1,'B', 2, 2, 0, 1);
;with cte_a as
(
SELECT proce, max(addi) as Aadd, max(sub) as Asub, max(multi) as Amulti, max(div) as Adiv
FROM #table where type = 'A'
group by proce
),cte_b as
(
SELECT proce, max(addi) as Badd, max(sub) as Bsub, max(multi) as Bmulti, max(div) as Bdiv
FROM #table where type = 'B'
group by proce
)
SELECT a.proce,a.aAdd, a.aSub, a.Amulti, a.Adiv,b.BAdd,b.bsub, b.bmulti, b.bdiv
from cte_a as a
join cte_b as b
on a.Proce = b.Proce
proce
aAdd
aSub
Amulti
Adiv
BAdd
bsub
bmulti
bdiv
1
1
0
1
1
2
2
0
1

how to sum count sql

How to total count?
SELECT
COUNT(CASE WHEN SHP.id = 1 then 1 ELSE NULL END) as "New",
COUNT(CASE WHEN SHP.id = 2 then 5 ELSE NULL END) as "Accepted"
from SHP
RESULT:
NEW Accepted
1 5
But I need a total count
result: 6
I'd do something like this;
SELECT
COUNT(CASE WHEN id = 1 THEN 1 END) as New,
COUNT(CASE WHEN id = 2 THEN 5 END) as Accepted,
COUNT(CASE WHEN id = 1 THEN 1
WHEN id = 2 THEN 5 END) as Total
FROM SHP
This is exactly what the CASE statement should be used for, the logic is very simple. This will avoid having to perform multiple calculations on the same fields.
As a note, the value in your THEN statement isn't used in this instance at all, it's just doing a COUNT of the number rather than performing a SUM. I've also removed the ELSE NULL because this is what the CASE will do by default anyway.
If your intention was to SUM the values then do this;
SELECT
SUM(CASE WHEN id = 1 THEN 1 END) as New,
SUM(CASE WHEN id = 2 THEN 5 END) as Accepted,
SUM(CASE WHEN id = 1 THEN 1
WHEN id = 2 THEN 5 END) as Total
FROM SHP
Example
Assuming you have only two values in your database, 1 and 2, we can create test data like this;
CREATE TABLE #SHP (id int)
INSERT INTO #SHP (id)
VALUES (1),(2)
And use this query;
SELECT
SUM(CASE WHEN id = 1 then 1 END) as New,
SUM(CASE WHEN id = 2 then 5 END) as Accepted,
SUM(CASE WHEN id = 1 THEN 1
WHEN id = 2 THEN 5 END) as Total
FROM #SHP
Gives this result;
New Accepted Total
1 5 6
Try this:
SELECT
COUNT(CASE WHEN SHP.id = 1 then 1 ELSE NULL END) +
COUNT(CASE WHEN SHP.id = 2 then 5 ELSE NULL END) as "Total"
from SHP
You could wrap your query into a subquery and do something like this:
SELECT SUM(New) as New, Sum(Accepted) as Accepted, Sum(New + Accepted) as Total FROM
(SELECT
COUNT(CASE WHEN SHP.id = 1 then 1 ELSE NULL END) as "New",
COUNT(CASE WHEN SHP.id = 2 then 5 ELSE NULL END) as "Accepted"
from SHP) as SubQuery
That's if you don't want to duplicate doing the counts and just adding the two together.
try this
with s1 as(
SELECT
COUNT(CASE WHEN SHP.id = 1 then 1 ELSE 0 END) as "New"
from SHP
),s2 as
(
SELECT
COUNT(CASE WHEN SHP.id = 2 then 5 ELSE 0 END) as "Accepted"
from SHP
)
select sum("New"+ "Accepted") from s1,s2

Case statement with grouping

Can you help me write a SELECT statement that returns a single row having columns for each TypeId involved for the transaction number 55?
CREATE TABLE Types
(
Id INT IDENTITY(1,1) NOT NULL,
Name VARCHAR(100) NOT NULL,
CONSTRAINT PK_Types PRIMARY KEY CLUSTERED(Id)
)
GO
INSERT INTO Types
VALUES
('Type1')
,('Type2')
,('Type3')
,('Type4')
,('Type5')
GO
CREATE TABLE Transactions
(
Id INT IDENTITY(1000,1) NOT NULL,
TypeId INT NULL,
TransactionNumber INT NOT NULL,
Amount MONEY NULL,
DateRecorded DATETIME2 NOT NULL,
CONSTRAINT PK_Transactions PRIMARY KEY CLUSTERED(Id),
CONSTRAINT FK_Types FOREIGN KEY(TypeId) REFERENCES Types(Id)
)
GO
INSERT INTO Transactions
VALUES
(1,55,2555.50,SYSDATETIME())
,(3,55,3555.50,SYSDATETIME())
,(4,55,4555.50,SYSDATETIME())
,(5,55,5555.50,SYSDATETIME())
GO
I need a single row returned for each transaction number in the Transactions table.
What I already tried:
SELECT TransactionNumber
,(CASE WHEN TypeId = 1 THEN Amount ELSE 0 END) AS Type1
,(CASE WHEN TypeId = 2 THEN Amount ELSE 0 END) AS Type2
,(CASE WHEN TypeId = 3 THEN Amount ELSE 0 END) AS Type3
,(CASE WHEN TypeId = 4 THEN Amount ELSE 0 END) AS Type4
,(CASE WHEN TypeId = 5 THEN Amount ELSE 0 END) AS Type5
FROM Transactions
SELECT TransactionNumber
,sum(CASE WHEN TypeId = 1 THEN Amount ELSE 0 END) AS Type1
,sum(CASE WHEN TypeId = 2 THEN Amount ELSE 0 END) AS Type2
,sum(CASE WHEN TypeId = 3 THEN Amount ELSE 0 END) AS Type3
,sum(CASE WHEN TypeId = 4 THEN Amount ELSE 0 END) AS Type4
,sum(CASE WHEN TypeId = 5 THEN Amount ELSE 0 END) AS Type5
FROM Transactions group by TransactionNumber;
I think you can do a PIVOT to get required output:
SELECT *
FROM (
SELECT ty.NAME, ISNULL(Amount,0)Amount
FROM TRANSACTIONS t
INNER JOIN Types ty ON ty.Id = t.TypeId
WHERE TransactionNumber = 55
) sub
PIVOT(
SUM(Amount) FOR [Name] IN ([Type1], [Type2], [Type3], [Type4], [Type5])
) AS pivottable
SQL Fiddle
With conditional aggregation:
select Id,
sum(case TypeId when 1 then Amount end) Type1,
sum(case TypeId when 2 then Amount end) Type2,
...
from Transactions
group by Id
I think this would be the query you are looking for:
SELECT
COUNT(CASE WHEN TypeID = 1 THEN 1 ELSE NULL END) '# Transactions Type 1'
, COUNT(CASE WHEN TypeID = 2 THEN 1 ELSE NULL END) '# Transactions Type 2'
, COUNT(CASE WHEN TypeID = 3 THEN 1 ELSE NULL END) '# Transactions Type 3'
, COUNT(CASE WHEN TypeID = 4 THEN 1 ELSE NULL END) '# Transactions Type 4'
, COUNT(CASE WHEN TypeID = 5 THEN 1 ELSE NULL END) '# Transactions Type 5'
FROM TRANSACTIONS
Where TransactionNumber = 55
You can find a working SQLFiddle here.
EDIT:
After you comment I think what you are actually looking for is SUM().
SELECT TransactionNumber
, SUM(CASE WHEN TypeId = 1 THEN Amount ELSE 0 END) AS Type1
, SUM(CASE WHEN TypeId = 2 THEN Amount ELSE 0 END) AS Type2
, SUM(CASE WHEN TypeId = 3 THEN Amount ELSE 0 END) AS Type3
, SUM(CASE WHEN TypeId = 4 THEN Amount ELSE 0 END) AS Type4
, SUM(CASE WHEN TypeId = 5 THEN Amount ELSE 0 END) AS Type5
FROM Transactions
GROUP BY TransactionNumber
SQLFiddle for 2nd query here.

Insert Data Into temporary table using Select * Into

I want to insert data into temporary table for that i am using select * into syntax.
But i am getting error :
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near ')'.
Though Single Query getting executed successful.
Code:
Create Table #_Total
(
A Int,
B Int,
C Int,
D Int
)
Select * InTo #_Total From(
Select
Sum(Case When Closed=0 And ISNULL(VendorTicketNo,'')='' Then 1 Else 0 End),
Sum(Case When Closed=1 And TicketType<>8 AND ISNULL(VendorTicketNo,'')<>'' Then 1 Else 0 End),
Sum(Case When Closed=1 And CAST(ClosedOn As DATE)= CONVERT(VARCHAR(8),GETDATE(),112) Then 1 Else 0 End),
Sum(Case When Closed=0 And TicketType=8 Then 1 Else 0 End)
From ALBATMStatus.dbo.Ticket
)
Select * From #_Total
Database - SQL SERVER 2008
Since you are creating the table before hand, you have to use
INSERT INTO
Try this
Create Table #_Total
(
A Int,
B Int,
C Int,
D Int
)
Insert Into #_Total
Select * From(
Select
Sum(Case When Closed=0 And ISNULL(VendorTicketNo,'')='' Then 1 Else 0 End),
Sum(Case When Closed=1 And TicketType<>8 AND ISNULL(VendorTicketNo,'')<>'' Then 1 Else 0 End),
Sum(Case When Closed=1 And CAST(ClosedOn As DATE)= CONVERT(VARCHAR(8),GETDATE(),112) Then 1 Else 0 End),
Sum(Case When Closed=0 And TicketType=8 Then 1 Else 0 End)
From ALBATMStatus.dbo.Ticket
) AS a
Select * From #_Total
Raj
As #Raj said you either use Create or select into.
However he missed as ALIAS_NAME. It is as below :
Create Table #_Total
(
A Int,
B Int,
C Int,
D Int
)
Insert Into #_Total
Select * From(
Select
Sum(Case When Closed=0 And ISNULL(VendorTicketNo,'')='' Then 1 Else 0 End) A,
Sum(Case When Closed=1 And TicketType<>8 AND ISNULL(VendorTicketNo,'')<>'' Then 1 Else 0 End) B,
Sum(Case When Closed=1 And CAST(ClosedOn As DATE)= CONVERT(VARCHAR(8),GETDATE(),112) Then 1 Else 0 End) C,
Sum(Case When Closed=0 And TicketType=8 Then 1 Else 0 End) D
From ALBATMStatus.dbo.Ticket
) as q1
Select * From #_Total

Adding values in a table in SQL 2008

Trying to get a basic understanding of T-SQL here in SQL Server 2008. Suppose I have a table named "Issues" with columns such as:
Priority User
1 Foo
1 Foo
2 Foo
5 Foo
4 Bar
5 Bar
1 Bar
1 Fuz
and I wish to display a count of the Priority for each User, along with a breakdown of each Priority, such that the resulting table might be named "Breakdown" might look like
User Total 1 2 3 4 5
Foo 4 2 1 0 0 1
Bar 3 1 0 0 1 1
Fuz 1 1 0 0 0 0
I was thinking I might declare variables and write my query something like
DECLARE #P1 INT
DECLARE #P2 INT
DECLARE #P3 INT
DECLARE #P4 INT
DECLARE #P5 INT
SELECT COUNT(id) AS Total,UserName,
CASE Priority
WHEN 1 Then #P1 = #P1 + 1
WHEN 2 Then #P2 = #P2 + 1
WHEN 3 Then #P3 = #P3 + 1
WHEN 4 Then #P4 = #P4 + 1
WHEN 5 Then #P5 = #P5 + 1
END,
FROM Breakdown
GROUP BY UserName
but I'm pretty sure I'm on the wrong track. Does anyone have any suggestions?
Thanks, and sorry for the noobish question; but I'm not sure exactly what to google for here...
-R.
Use:
SELECT i.user,
COUNT(i.priority) AS total,
SUM(CASE WHEN i.priority = 1 THEN 1 ELSE 0 END) AS 1,
SUM(CASE WHEN i.priority = 2 THEN 1 ELSE 0 END) AS 2,
SUM(CASE WHEN i.priority = 3 THEN 1 ELSE 0 END) AS 3,
SUM(CASE WHEN i.priority = 4 THEN 1 ELSE 0 END) AS 4,
SUM(CASE WHEN i.priority = 5 THEN 1 ELSE 0 END) AS 5
FROM ISSUES i
GROUP BY i.user
It's a pivot query, converting row data into columnar data.
Not a noob/beginner issue to deal with. SQL Server 2005+ added the (now ANSI) PIVOT/UNPIVOT syntax, but this is portable to most databases (because few currently support PIVOT/UNPIVOT).
You need to SELECT one column for each column you want in your result set. In your SQL, you're only selecting three columns. Try:
SELECT UserName,
Count(*) AS Total,
SUM(CASE Priority WHEN 1 THEN 1 ELSE 0 END) AS P1_Total,
SUM(CASE Priority WHEN 2 THEN 1 ELSE 0 END) AS P2_Total,
SUM(CASE Priority WHEN 3 THEN 1 ELSE 0 END) AS P3_Total,
SUM(CASE Priority WHEN 4 THEN 1 ELSE 0 END) AS P4_Total,
SUM(CASE Priority WHEN 5 THEN 1 ELSE 0 END) AS P5_Total
FROM Issues
GROUP BY UserName