T-SQL (SS2K8) :: Using Case Statement In Pivot?

Jun 23, 2015

Can we use case in pivot like below? I am getting an error. I want to do Pivot on condition basis.

select (
Column1
,Column2
,Column3
,Column4
,coloumn5
from Mytable
) x
pivot
(
case when Column1 = 6 then sum(Column3) else max(Column4) End
for coloumn5 in (' + @COLS + ')
)p

View 2 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Using CASE Statement Within A PIVOT

Jun 17, 2014

I am using a PIVOT function to obtain the Invoice Values, but they appear in different currencies so need to perform a case function.

But am struggling with the syntax;

This fails a syntax check with
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'Case'.

[Code]....

View 2 Replies View Related

T-SQL (SS2K8) :: Using Case Within PIVOT Portion Of Crosstab Query

Apr 13, 2015

I have created a crosstab query using the Pivot statement that returns the expected results. The results look similar to the sample below:

ItemKey Description Aflatoxin Coliform Bacteria E_Coli Fumonisin Melamine Moisture Mold Salmonella Vomitoxin (DON) Yeast

1000 Item1000 1 0 0 1 0 1 0 1 1 0
1024 Item1024 1 0 0 1 0 1 0 1 1 0
135 Item135 1 0 0 1 0 1 0 1 1 0
107 Item107 0 0 0 0 0 1 0 1 1 0
106 Item106 1 0 0 1 0 1 0 1 1 0

I'm using this statement to create the result set:

SELECT ItemKey, Description, Aflatoxin, [Coliform Bacteria], [E_Coli],[Fumonisin],
Melamine,Moisture, Mold, Salmonella, [Vomitoxin (DON)], Yeast
FROM
(SELECT tblInventory.ItemKey, tblInventory.Description,
jctProductClassificationRequiredTest.ProductTestClassID, tlbTestType.TestDescription

[Code] .....

Instead of doing a Count for the Pivot (the count will always be either 0 or 1 due to the design of the table being used), I would like to return an "X" for those records with a count of 1, and return a blank (otherwise null) for those records with a count of 0. So, the result set would look like:

ItemKey Description Aflatoxin Coliform Bacteria E_Coli Fumonisin Melamine Moisture Mold Salmonella Vomitoxin (DON) Yeast
1000 Item1000 X X X X X
1024 Item1024 X X X X X
135 Item135 X X X X X
107 Item107 X X X
106 Item106 X X X X X

I tried using a Case statement within the PIVOT portion, but I either did it incorrectly or it's not possible to do use a Case within the Pivot. Can I easily accomplish this?

View 6 Replies View Related

T-SQL (SS2K8) :: Statement Using Case And Join Together

Jan 29, 2015

I am trying to use this logic into a query:

Select P.S,E.S,E.R
from Pack P(nolock)
join Exp E on P.Id=E.O
on E.R is null
case when E.R is not null then ''
else ''
end
where P.s='PLT000044'

I have to query two conditions joining the tables. when E.R is NULL and when E.R is not null. but the value is coming from the join between the 2 tables :P and E.

View 2 Replies View Related

T-SQL (SS2K8) :: Case Statement In The Where Clause?

Jun 5, 2015

I have a population split between two vendors. One gets last names between A and R, the other the rest. Now, on a given date vendor 1 gets everybody.

I can accomplish this with a case statement on the upper range (R or Z), but it seems I should be able to do this without testing at all after the turnover date.

A small bit of the code:

declare @get_date datetime = convert(char(10),getdate(),101)
select top 10 pt.pt_id, pt.last_name
fromsmsmir.mir_acct a join smsmir.mir_pt pt on (a.src_sys_id = pt.src_sys_id
and a.pt_id = pt.pt_id
and a.from_file_ind = pt.from_file_ind

[Code] ....

Seems I should be able to not test the last name after the turnover date, but I can't figure out how.

View 2 Replies View Related

T-SQL (SS2K8) :: How To Execute SP In Select Case Statement

Mar 20, 2014

I am a junior dba not a developer. So I'm just trying to get use to write code in T-SQL.

Anyways, I have a table which is dba.dbhakyedek.

Columns are

dbname, username, class_desc, object_name, permission_name, state_desc

I have statement

select case
when class_desc='OBJECT_OR_COLUMN' then 'GRANT '+permission_name+' ON '+'['+left(object_name,3)+'].'+'['+substring(object_name,5,len(object_name))+ '] TO '+username
WHEN class_desc='DATABASE_ROLE' THEN EXEC sp_addrolemember N'object_name', N'MC'
end
from dba.dbhakyedek
where username='MC'

This statement was running successfully until exec sp_addrolemember thing. I just learned that i can't call a sp in select case but i couldnt figure out how to do it.

View 6 Replies View Related

T-SQL (SS2K8) :: Update With Case Statement Not Working?

May 29, 2014

I have a situation where I want to update a column if and only if it is null.

UPDATE Employee
SET VEmployeeID = CASE WHEN E.VEmployeeID IS NULL
THEN ves.VEmployeeID
END
FROM Employee E
INNER JOIN VEmployeeStaging VES
ON E.EID= VES.EID

But what happens is when I run the procedure every other time I run it, it changes everything to null. The other times it puts the VEmployeeID in.

So what is happening is the times when it is not null (where it is not supposed to do anything) it puts a null in. The next time it works.

View 6 Replies View Related

T-SQL (SS2K8) :: Dividing Two Rows Within CASE Statement

Jul 28, 2014

I was given the task to come up with a result set based on certain criteria:

Please add one row for each offer code

1) Opt-in rate by offer code: This can be calculated by dividing XXX Inventory with lead / XXX Inventory (A)

The report should read something like below:

Example result set:

Log Date: OfferLetter OfferCode DailyCount

2014-07-20 A XXX Inventory (A) 108
2014-07-20 A XXX Inventory with lead 54
2014-07-20 A XXX Inventory Opt-in Rate: 50%

There are 12 different groupings and OfferLetter A is just one of them.

Below is the code that is written to date:

DECLARE @Start datetime = DATEADD(day, DATEDIFF(day, 0, GETDATE() - 8), 0)
DECLARE @End datetime = DATEADD(day, DATEDIFF(day, 0, GETDATE() - 1) + 1, 0)
DECLARE @Today datetime = DATEADD(day, DATEDIFF(day, 0, GETDATE() - 1), 0);

SELECTDT.OfferCode, DT.OfferCodeDesc
INTO#tempOfferCodes

[Code] ....

The issue I'm having is that the values I need to divide by are in fact, a result set from the CASE statement. It's been a long time since I've done anything like this.

View 2 Replies View Related

T-SQL (SS2K8) :: Using A Date Comparison In A Case Statement?

Mar 19, 2015

I am trying to use a date comparison in a statement using the year statement as well. Here is what I have:

Case [LastHireDate]
When YEAR([LastHireDate]) < Year(@EndYearlyDate) then '12'
When Month([LastHireDate]) = '1' then '12'
When Month([LastHireDate]) = '2' then '11'
When Month([LastHireDate]) = '3' then '10'
When Month([LastHireDate]) = '4' then '9'

[Code] ....

When I am looking at it [LastHireDate] is showing that red line underneath. The < symbol has a red line and @EndYearlyDate has a red line. I can not seem to get them to clear and am, wondering what I am missing. When I execute the error comes up that it does not like the < sign in there.

Here is the full piece that the Case resides in:

Insert _Test
SELECT
EmpNo,
PersonIdNo,
REPLACE(PersonTaxIdNo,'-',''),
LastName,
FirstName,

[code]......

View 3 Replies View Related

Pivot With Case

Jul 21, 2013

I have a pivot script but I would like to use a case statement,See below script and result

select top 10 id,

[1421],
[1420],
[1419],
[1418]
from (

select Purchaseid,Purchaseid as id, occasionid, transactionid
from ticket_facts ) as query
pivot (count(transactionid) for purchaseid

in (
[1421],
[1420],
[1419],
[1418])) as piv

[code]....

I would like the count to be

case (count(transactionid) when >0 then 1 else 0) end

how would I use the case statement with the pivot.

View 17 Replies View Related

Problem Using Result From CASE In Another CASE Statement

Nov 5, 2007

I have a view where I'm using a series of conditions within a CASE statement to determine a numeric shipment status for a given row. In addition, I need to bring back the corresponding status text for that shipment status code.

Previously, I had been duplicating the CASE logic for both columns, like so:




Code Block...beginning of SQL view...
shipment_status =
CASE
[logic for condition 1]
THEN 1
WHEN [logic for condition 2]
THEN 2
WHEN [logic for condition 3]
THEN 3
WHEN [logic for condition 4]
THEN 4
ELSE 0
END,
shipment_status_text =
CASE
[logic for condition 1]
THEN 'Condition 1 text'
WHEN [logic for condition 2]
THEN 'Condition 2 text'
WHEN [logic for condition 3]
THEN 'Condition 3 text'
WHEN [logic for condition 4]
THEN 'Condition 4 text'
ELSE 'Error'
END,
...remainder of SQL view...






This works, but the logic for each of the case conditions is rather long. I'd like to move away from this for easier code management, plus I imagine that this isn't the best performance-wise.

This is what I'd like to do:



Code Block
...beginning of SQL view...
shipment_status =
CASE
[logic for condition 1]
THEN 1
WHEN [logic for condition 2]
THEN 2
WHEN [logic for condition 3]
THEN 3
WHEN [logic for condition 4]
THEN 4
ELSE 0
END,


shipment_status_text =

CASE shipment_status

WHEN 1 THEN 'Condition 1 text'

WHEN 2 THEN 'Condition 2 text'

WHEN 3 THEN 'Condition 3 text'

WHEN 4 THEN 'Condition 4 text'

ELSE 'Error'

END,
...remainder of SQL view...


This runs as a query, however all of the rows now should "Error" as the value for shipment_status_text.

Is what I'm trying to do even currently possible in T-SQL? If not, do you have any other suggestions for how I can accomplish the same result?

Thanks,

Jason

View 1 Replies View Related

PIVOT Is Not Case-sensitive

Oct 27, 2006

Hi there,

I am using a PIVOT to count the number of chunk for each block type:
ex.:
block_type, chunk
a, <data>
a, <data>
b, <data> ...

My problem is that the block_type is case-sensitive, 'a' should not be counted as a 'A'.
How can I take the case in consideration?

I've tried to plug a COLLATE SQL_Latin1_General_CP1_CS_AS statement but it doesn't seem to be supported... Something like:
SELECT *
FROM recv.test_Blocks
PIVOT (
COUNT(chunk)
FOR block_type COLLATE SQL_Latin1_General_CP1_CS_AS
IN ([9.], a, B, h, q)
) AS pvt

Also something like:
IN (a, A)
returns an error: The column 'A' was specified multiple times for 'pvt'.

Thanks

View 1 Replies View Related

Ordering Pivot Table Using Case Else

Aug 27, 2007

I have created a Pivot table using Case Else with a combination of Row_Number function. What I'm looking for is to try to Order it in a specific way. Manivannan.D.Sekaran, helped me with another Pivot table that I had and it worked great. So I decided to learn how to do a Pivot table using Case Else. Sample Data is the following without the Case Else


UserID LastName FirstName DocumentDesc docFileName
1 Smith Paul Resume PSmithResume.pdf
1 Smith Paul PhdStatistics phdstatstranscript.pdf
1 Smith Paul MS Applied Statistics MsAStats.pdf
1 Smith Paul MS Operation Research MsOpResearch.pdf
2 Jackson Jane MS Information Systems MsInforSystems.pdf
2 Jackson Jane Resume JaneJacksonResume.pdf

This is my query for my Pivot using Case Else:




Code Snippet
Select UserID, LastName, FirstName,
MAX(Case When RecID=1 Then DocumentDesc Else '' End)As Document1,
Max(Case When RecID=1 Then docFileName Else '' End) As DocumentFileName,
Max(Case When RecID=2 Then DocumentDesc Else '' End)As Document2,
Max(Case When RecID=2 Then docFileName Else '' End) As DocumentFileName,
Max(Case When RecID=3 Then DocumentDesc Else '' End)As Document3,
MAX(Case When RecID=3 Then docFileName Else '' End) As DocumentFileName,
Max(Case When RecID=4 Then DocumentDesc Else '' End)As Document4,
Max(Case When RecID=4 Then docFileName Else '' End) As DocumentFileName,
Max(Case When RecID=5 Then DocumentDesc Else '' End)As Document5,
Max(Case When RecID=5 Then docFileName Else '' End) As DocumentFileName,
Max(Case When RecID=6 Then DocumentDesc Else '' End)As Document6,
Max(Case When RecID=6 Then docFileName Else '' End)As DocumentFileName
From (
Select a.UserID, a.LastName, a.FirstName, b.FileName, b.DocumentDesc, b.DocumentTypeID, ROW_NUMBER() OVER(PARTITION BY a.UserID ORDER BY a.UserID) AS RecID
FROM Person a JOIN
Documents b ON
a.UserID = b.UserID
Where b.DocumentTypeID = '126d2beb-f7a1-4bf1-b9c0-dded37d3a6bc' Or b.DocumentTypeID = '9087956e-1fb0-4f3d-ba33-ef31d79141af'
) X
Group by UserID, LastName, Firstname
Order by LastName







Code Snippet
The Output is the following with the Pivot applied: (I'm excluding UserID, LastName, FirstName for space purposes)

The column headings are:

Document1 DocumentFileName Document2 DocumentFileName Document3 DocumentFileName Document4 DocFilename

The Data for document and filename columns:

Ms Information Systems MsInforSystems.pdf Resume JaneJacksonResume.pdf

Resume PSmithResume.pdf PhdStatistics Phdstatstranscript.pdf Ms Applied Statistics MsAstats.pdf






What I want is to have the column called Document1 to have only Resumes and the rest of the other columns to have the other files.

The following data places the data into one table.

Create Table #data (
[UserID] int ,
[LastName] Varchar(100) ,
[FirstName] Varchar(100) ,
[DocumentDesc] Varchar(100) ,
[docFileName] Varchar(100)
);

Insert Into #data Values('1','Smith','Paul','Resume','PSmithResume.pdf');
Insert Into #data Values('1','Smith','Paul','PhdStatistics','phdstatstranscript.pdf');
Insert Into #data Values('1','Smith','Paul','MSAppliedStatistics','MsAstats.pdf');
Insert Into #data Values('1','Smith','Paul','MSOperationResearch', 'MsOpResearch.pdf');
Insert Into #data Values('2','Jackson','Jane','MsInformationSystems', 'MsInforSystems.pdf');
Insert Into #data Values('2','Jackson','Jane','Resume', 'JaneJacksonResume.pdf');

View 4 Replies View Related

T-SQL (SS2K8) :: PIVOT Without Aggregation

Jun 28, 2015

I have a table imported from a legacy Oracle database that stores values vertically in name/value pairs. I store it in table-type variable that is an exact copy of the structure:

DECLARE @OracleEngData TABLE
( DataSourceCHAR(8)
, [OMNI_NUMBER] INTEGER
, [TIMESTAMP] INTEGER
, [DATA_TYPE] NVARCHAR(24)
, [PARAMETER] NVARCHAR(32)
, [PARAMETER_VALUE] NVARCHAR(132));

If this information were pivoted horizontally: OMNI_NUMBER would be the primary key.

TIMESTAMP is a 10-digit integer that represents the number of seconds since 1/1/1970 UTC that requires additional conversion. DATA_TYPE is not the data type. It is a general categorization of the next two columns.PARAMTER would be the column headings if it were horizontal..PARAMETER_VALUE would be the data value in that column.

I would like to try to use PIVOT to list the PARAMETER column values as column headers. This seems to work fine. What's confusing me is that I'd like it to list the PARAMETER_VALUE column values as raw data, just as it is in the source version, without having to apply some sort of aggregate function to it. Here's a CSV sample of the data you can paste into Excel. I'm trying to transform this:

OMNI_NUMBER,TIMESTAMP,DATA_TYPE,PARAMETER,PARAMETE_VALUE
506026,1413240436,test_data,cnr,211250000,54.8
506026,1413244259,test_data,cnr,211250000,53.2
506026,1413244679,test_data,cnr,211250000,53.1
506026,1413309646,test_data,cnr,211250000,53.4
506026,1413315987,test_data,cnr,211250000,53

[code]...

But I don't want the sum of the values or the average of the values, just the values. The PIVOT syntax seems to require an aggregate operation.

View 2 Replies View Related

Subquery, Select Case, Pivot Help. Is There An Easier Way?

Apr 12, 2008



I'm trying to select from a table with three columns. I want these columns to be spread out among multiple columns based on the values. I hope someone can shed some light on this. I might be able to use pivot, but don't know how the syntax would roll for this.

Here is the example of dummy values and the output I am trying to obtain.




drop table table1

create table table1

(Category int, Place int, Value int)

insert into table1 values

(1, 1, 20)

insert into table1 values

(1,2, 12)

insert into table1 values

(1,3, 30)

insert into table1 values

(2,1, 34)

insert into table1 values

(2,2, 15)

insert into table1 values

(2,3, 78)



select Category,

(select top 1 value from table1 where place = 1 and Category = t1.Category) as place1,

(select top 1 value from table1 where place = 2 and Category = t1.Category) as place2,

(select top 1 value from table1 where place = 3 and Category = t1.Category) as place3

from Table1 t1

group by Category




Thanks for the help.

View 5 Replies View Related

T-SQL (SS2K8) :: Pivot And Unpivot In Same Query?

Feb 15, 2014

I have below table and within same query i need pivot and unpivot.

create table #temp(name1 varchar(10),name2 varchar(10),name3 varchar(10),month date,emp1 int,emp2 int,emp3 int,emp4 int)
insert into #temp values ('a','b','c','1-1-2013',1,2,3,4)
insert into #temp values ('a','b','c','1-2-2013',11,20,30,40)
insert into #temp values ('a','c','c','1-1-2013',22,30,80,40)
insert into #temp values ('a','c','c','1-2-2013',28,34,39,30)
select * from #temp

Now i need output in below format

name1,name2,name3,Emp,jan-13,feb-13
a,b,c,emp1,1,11
a,b,c,emp2,2,20
a,b,c,emp3,3,30
a,b,c,emp4,4,40
a,c,c,emp1,22,28
a,c,c,emp2,30,34
a,c,c,emp3,80,39
a,c,c,emp4,40,30

View 4 Replies View Related

T-SQL (SS2K8) :: Incorrect Syntax Near Keyword (pivot)

Oct 8, 2014

I'm struggling with one Syntax error

CREATE TABLE #ToolCompliance
(
SOFTWAR_ID INT
,CONTROL_CODE VARCHAR(100)
,CONTROL_STATUS VARCHAR(100)
)
INSERT INTO #ToolCompliance
VALUES(1000,'AC','SUCCESS')

[code]....

View 4 Replies View Related

T-SQL (SS2K8) :: Transpose / Pivot Textual Data

Jan 19, 2015

In our contract management system, each contract has over 100 reference fields attached to it. These are all stored in single table with contract ID, reference GUID and value as the columns.

So you will have multiple rows for each contract....one for each of the reference fields and then the value attached to that reference.

I want to return the data so there is one row per contract with the reference fields as columns and the reference field values as the column data.

Can this be done using PIVOT as I have tried but not had any success?

View 6 Replies View Related

T-SQL (SS2K8) :: Possible Pivot / CTE Recursion Restructuring Of Data

Sep 7, 2015

I have a table (folderstructure) with the following columns:

pcmid, cmid, foldername
pcmid is the parent directory
cmid is the directory
foldername is the name of the directory

e.g. note, number of levels are unknown

cmid pcmid name
1 NULL c:
101 1 level1
201 101 level2
45 101 level2a
56 201 level3
57 201 level3a

I'm looking to create a table that has cmid followed by the full directory path

So either (using above):

cmid path
1 c:
101 c:level1
201 c:level1level2
45 c:level1level2a
56 c:level1level2level3
57 c:level1level2level3a

etc.

OR

cmid 1 2 3 4
1 c:
101 c: level1
201 c: level1 level2
45 c: level1 level2a
56 c: level1 level2 level3
57 c: level1 level2 level3a

etc.

I've can use recursion to allocate a level to each name /cmid/pcmid combination

I could use multiple self joins

Is there a way this can be achieved using pivots or CTE recursion or something else...

View 2 Replies View Related

SQL Server 2012 :: Update Statement With CASE Statement?

Aug 13, 2014

i was tasked to created an UPDATE statement for 6 tables , i would like to update 4 columns within the 6 tables , they all contains the same column names. the table gets its information from the source table, however the data that is transferd to the 6 tables are sometimes incorrect , i need to write a UPDATE statement that will automatically correct the data. the Update statement should also contact a where clause

the columns are [No] , [Salesperson Code], [Country Code] and [Country Name]

i was thinking of doing

Update [tablename]
SET [No] =
CASE
WHEN [No] ='AF01' THEN 'Country Code' = 'ZA7' AND 'Country Name' = 'South Africa'
ELSE 'Null'
END

What is the best way to script this

View 1 Replies View Related

How To Write Select Statement Inside CASE Statement ?

Jul 4, 2006

Hello friends,
I want to use select statement in a CASE inside procedure.
can I do it? of yes then how can i do it ?

following part of the procedure clears my requirement.

SELECT E.EmployeeID,
CASE E.EmployeeType
WHEN 1 THEN
select * from Tbl1
WHEN 2 THEN
select * from Tbl2
WHEN 3 THEN
select * from Tbl3
END
FROM EMPLOYEE E

can any one help me in this?
please give me a sample query.

Thanks and Regards,
Kiran Suthar

View 7 Replies View Related

Transact SQL :: Update Statement In Select Case Statement

May 5, 2015

I am attempting to run update statements within a SELECT CASE statement.

Select case x.field
WHEN 'XXX' THEN
  UPDATE TABLE1
   SET TABLE1.FIELD2 = 1
  ELSE
   UPDATE TABLE2
   SET TABLE2.FIELD1 = 2
END
FROM OuterTable x

I get incorrect syntax near the keyword 'update'.

View 7 Replies View Related

T-SQL (SS2K8) :: Join Or Pivot / Unpivot For Mismatch Dates

Jul 31, 2014

I have a table which uses multiple joins to create another table but it turns out that the effective_date which is used in the join to match row together does not work all the time since some of the dates for the effective date column are out of sync meaning records that show data as missing even when the other table contains the data. I try the SQL script below but it returning 6 rows instead of 3–

select t2.[entity_id]
,t2.[effective_date]
,[company_name]
,[last_accounts_date]
,[s_code]
,[s_code_description]
,[ineffective_date]

[code]....

View 3 Replies View Related

T-SQL (SS2K8) :: Change Column Order In Dynamic Pivot?

Sep 17, 2014

I am creating dynamic pivot and my column order is as below

[2015-02],[2015-04] [Prior] ,[2014-08],[2014-11]

but i want to display as below:

[Prior],[2014-08],[2014-11],[2015-02],[2015-04]

View 1 Replies View Related

T-SQL (SS2K8) :: Pivot When Don't Know Amount Of Columns And Column Names

Jan 7, 2015

I am trying to figure out how to pivot a temporary table. I have a table which starts with a date but the number of columns and columns names will vary but will be type INT (Data, col2,col3,col4………….n)

So it could look like

Date , TS-Sales, Budget , Toms sales
01-Jan-14,100,120,300
02-Jan-14,80,150,300
03-Jan-14,100,20,180

Turned to this

01-jan-14, 02-jan-14, 03-jan-14
100,80,100
120,150,20
300,300,180

Or even just the date and a SUM

What I want is to be able to sum al the columns but without knowing the name and the amount columns to start with this is a manually processes. How could I automate this?

View 2 Replies View Related

Case Statement Error In An Insert Statement

May 26, 2006

Hi All,
I've looked through the forum hoping I'm not the only one with this issue but alas, I have found nothing so I'm hoping someone out there will give me some assistance.
My problem is the case statement in my Insert Statement. My overall goal is to insert records from one table to another. But I need to be able to assign a specific value to the incoming data and thought the case statement would be the best way of doing it. I must be doing something wrong but I can't seem to see it.

Here is my code:
Insert into myTblA
(TblA_ID,
mycasefield =
case
when mycasefield = 1 then 99861
when mycasefield = 2 then 99862
when mycasefield = 3 then 99863
when mycasefield = 4 then 99864
when mycasefield = 5 then 99865
when mycasefield = 6 then 99866
when mycasefield = 7 then 99867
when mycasefield = 8 then 99868
when mycasefield = 9 then 99855
when mycasefield = 10 then 99839
end,
alt_min,
alt_max,
longitude,
latitude
(
Select MTB.LocationID
MTB.model_ID
MTB.elevation, --alt min
null, --alt max
MTB.longitude, --longitude
MTB.latitude --latitude
from MyTblB MTB
);

The error I'm getting is:
Incorrect syntax near '='.

I have tried various versions of the case statement based on examples I have found but nothing works.
I would greatly appreciate any assistance with this one. I've been smacking my head against the wall for awhile trying to find a solution.

View 10 Replies View Related

How To Show Records Using Sql Case Statement Or If Else Statement

Feb 20, 2008

i want to display records as per if else condition in ms sql query,for this i have used tables ,queries as follows


as per data in MS Sql

my tables are as follows
1)material
fields are -- material_id,project_type,project_id,qty, --

2)AB_Corporate_project
fields are-- ab_crp_id,custname,contract_no,field_no

3)Other_project
fields are -- other_proj_id,other_custname,po

for ex :
vales in table's are
AB_Corporate_project
=====================
ab_crp_id custname contract_no field_no
1 abc 234 66
2 xyz 33 20

Other_project
============
other_proj_id other_custname po
1 xxcx 111
2 dsd 222

material
=========
material_id project_type project_id qty
1 AB Corporate 1 3
2 Other Project 2 7

i have taken AB Corporate for AB_Corporate_project ,Other Project for Other_project


sample query i write :--

select m.material_id ,m.project_type,m.project_id,m.qty,ab.ab_crp_id,
ab.custname ,op.other_proj_id,op.other_custname,op. po
case if m.project_type = 'AB Corporate' then
select * from AB_Corporate_project where ab.ab_crp_id = m.project_id
else if m.project_type = 'Other Project' then
select * from Other_project where op.other_proj_id=m.project_id
end
from material m,AB_Corporate_project ab,Other_project op


but this query not work,also it gives errors

i want sql query to show data as follows


material_id project_type project_id custname other_custname qty
1 AB Corporate 1 abc -- 3
2 Other Project 2 -- dsd 7

so plz help me how can i write sql query for to show the output
plz send a sql query

View 8 Replies View Related

T-SQL (SS2K8) :: Pivot Data Based On Columns Value In Year Column

Jun 4, 2014

I am trying to pivot data based on columns value in year column... but results are not showing up correctly. I want to see all columns after pivot.I want to Pivot based on year shown in the data but it can be dynamic as year can go for last 3 years

I am also using an inner join as i have two amount columns in my code and i want to show both amount columns for all displayed year.I am able to pivot but I need in output all the columns like this Id,MainDate, Year1,Year2,Year3(if any), AMT1 for YR1, AMT2 for Yr1, , AMT1 for YR2, AMT2 for Yr2, AMT1 for YR3, AMT2 for Yr3,

Here is some data:

-- CREATE TABLE [dbo].[TEMP](
--[FileType] [varchar](19) NOT NULL,
--[dType] [char](2) NOT NULL,
--[dVersion] [char](2) NOT NULL,
--[Id] [char](25) NOT NULL,
--[MainDate] [char](40) NULL,

[code]....

View 5 Replies View Related

T-SQL (SS2K8) :: Get Current DB Backup Setup List In Pivot Style?

Dec 1, 2014

I need to list the current DB Backup Set up list in PIVOT STYLE.

I need following way:

Database_NameFULL - DDIFF - ILOG - L
DB1DL
DB2D
modelDL
DB3DIL
msdbD

View 2 Replies View Related

T-SQL (SS2K8) :: Case For Field Type

Jun 7, 2014

Is there an easy way to send back to my C# program the pascal case of a field type? If you get the parameters or columns for a table or procedure the type is in all lowercase (varchar instead of VarChar). But in C#, it is in an enum (SqlDbType) that has the variables as mixed case so you can't compare them and just pass the type. You need to figure out what the case should be - varchar should be VarChar and bigint should be BigInt.

View 1 Replies View Related

T-SQL (SS2K8) :: Pivot Table - How To Get Right Count In First Data Mining Replacing Zeros

Mar 24, 2014

I run this code:

SELECT
Gruppo_Assegnatario,
[100] as stato1, [101] as stato2, [102] as stato3
FROM
(
select

[Code] ...

That extracts only zeros (columns "stato1", "stato2", "stato3"):

Gruppo_Assegnatariostato1stato2stato3
SDB_BE Vita Antiriciclaggio0 00
SDB_BE Vita Assistenza clienti000
SDB_BE Vita Emissione000
SDB_BE Vita Gestione Rendite000
SDB_BE Vita Liquidazioni000

[Code] ....

Unlike the "SourceTable":

select
CASE_ID_,
Stato,
Gruppo_Assegnatario
FROM TicketInevasiPerGruppoEStato
extracts

CASE_ID_ Stato Gruppo_Assegnatario
HD0000003736734 AssegnatoSDB_GBS Variazione
HD0000003736739 AssegnatoSDB_GBS Variazione
HD0000003736743 AssegnatoSDB_GBS Variazione
HD0000003736783 AssegnatoSDB_GBS Variazione
HD0000003736806 SospesoSDB_BE Vita Selezione

[Code] ....

How can I get the right count in the first data mining replacing the zeros (columns "stato1", "stato2", "stato3")?

View 5 Replies View Related

T-SQL (SS2K8) :: How To Perform Mathematical Formula Without Using Case

Sep 17, 2014

I am having 4 Columns Qty decimal(12,3),CF1 Decimal(12,3),CF2 Decimal(12,3),Flag TinyInt.

I want to perform following without using case if it is possible.

When value of Flag is 0 then Qty*(CF2/CF1)
When value of Flag is 1 then Qty

And i Don't want to use any functions like isnull,NullIf,IIF even not union or union all.How to do this calculation without using any function.

Actually i am having more then 100000 rows in table and if i use functions then my index might not be called.,that why want to avoid cases and functions.

View 9 Replies View Related

T-SQL (SS2K8) :: Case Query - Unpivot Function

May 6, 2015

I've this result from my 'case' query;

Jan Feb Mar April
1 2 3 4

I want ;

Month Value
JAN 1
Feb 2
Mar 3
April 4

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved