SQL Server : multiple lines returned for CASE WHEN - sql

I am trying to select from a single table specific sets of data and then display them grouped under a single field. This however creates a line for each case statement.
I would ideally like to see a single line for each Quote with each of the fields against it.
Would anyone have any ideas how i could improve on what ive done so far?
select
KeyField as Quote,
CASE WHEN FieldName = 'QTY001' THEN AlphaValue ELSE null END as [QTY],
CASE WHEN FieldName = 'CON002' THEN AlphaValue ELSE null END as [Conductors],
CASE WHEN FieldName = 'COP001' THEN AlphaValue ELSE null END as [Copper Size],
CASE WHEN FieldName = 'COR001' THEN AlphaValue ELSE null END as [Core Length],
CASE WHEN FieldName = 'COR002' THEN AlphaValue ELSE null END as [Core Inside],
CASE WHEN FieldName = 'END001' THEN AlphaValue ELSE null END as [End Winding],
CASE WHEN FieldName = 'KV_001' THEN AlphaValue ELSE null END as [KV],
CASE WHEN FieldName = 'KW_001' THEN AlphaValue ELSE null END as [KW],
CASE WHEN FieldName = 'NAM001' THEN AlphaValue ELSE null END as [OEM],
CASE WHEN FieldName = 'SLO001' THEN AlphaValue ELSE null END as [Slots],
CASE WHEN FieldName = 'SPE001' THEN AlphaValue ELSE null END as [Speed],
CASE WHEN FieldName = 'TUR001' THEN AlphaValue ELSE null END as [Turns],
CASE WHEN FieldName = 'TYP001' THEN AlphaValue ELSE null END as [Type/Description]
from
AdmFormData
where
FormType = 'QOT'

add GROUP BY clause
SELECT ...,
MAX(CASE WHEN FieldName = 'QTY001' THEN AlphaValue ELSE null END) as [QTY],
.....
FROM...
WHERE...
GROUP BY KeyField

As an alternative to multiple case when ... statements, you could use SQLServer's PIVOT facility:
select
KeyField as Quote,
[QTY001] as [QTY],
[CON002] as [Conductors],
[COP001] as [Copper Size],
[COR001] as [Core Length],
[COR002] as [Core Inside],
[END001] as [End Winding],
[KV_001] as [KV],
[KW_001] as [KW],
[NAM001] as [OEM],
[SLO001] as [Slots],
[SPE001] as [Speed],
[TUR001] as [Turns],
[TYP001] as [Type/Description]
from
(select KeyField, FieldName, AlphaValue
from AdmFormData
where FormType ='QOT') as s
pivot
(max(AlphaValue) for FieldName in
([QTY001], [CON002], [COP001], [COR001], [COR002], [END001], [KV_001], [KW_001], [NAM001], [SLO001], [SPE001], [TUR001], [TYP001])
) as p

If you have MSSQL 2005 and above you can use PIVOT command:
SELECT KeyField, [QTY001], [CON002], [COR001]
FROM (
SELECT KeyField, FieldName, AlphaValue FROM data
) AS SourceTable
PIVOT (
MAX(AlphaValue)
FOR FieldName IN([QTY001], [CON002], [COR001])
) AS PivotTable
In other case, your solution is the only way to achieve that.
SQLFiddle

Related

mismatched input '(' expecting <EOF>(line 3, pos 28)

My code looks like this, I do not know why it raising an error, the error is in line 3 after case when, Can anyone help on this? thanks
SELECT
CASE
WHEN
(
CASE
WHEN
(
ltrim(rtrim(status)) = 'CANCELLED'
AND ltrim(rtrim(COALESCE(iscancelledwithte, - ))) = '0'
)
THEN
CASE
WHEN
(
mincancellationdate IS NULL
)
THEN
CASE
WHEN
(
lastupdatedts IS NULL
)
THEN
'9999-12-31'
ELSE
lastupdatedts
END
ELSE
mincancellationdate
END
ELSE
CASE
WHEN
(
approvedforbillingts IS NULL
)
THEN
'9999-12-31'
ELSE
approvedforbillingts
END
END
)
= '9999-12-31'
THEN
status
ELSE
'Closed'
END
AS casestatusname
FROM
tblrequesttemp AS tblrequests
I've paste your sql request into SQL Syntax Checker (https://www.eversql.com/sql-syntax-check-validator/), and it return an error in your coalesce function. I believe you forget the quotes around the tiret character.
There is the fixed SQL Request:
SELECT
CASE
WHEN (
CASE
WHEN (Ltrim(Rtrim(status)) = 'CANCELLED' AND ltrim(rtrim(coalesce(iscancelledwithte, '-'))) = '0') THEN
CASE
WHEN (mincancellationdate IS NULL) THEN
CASE
WHEN (lastupdatedts IS NULL) THEN '9999-12-31'
ELSE lastupdatedts
end
ELSE mincancellationdate
end
ELSE
CASE
WHEN (approvedforbillingts IS NULL) THEN '9999-12-31'
ELSE approvedforbillingts
end
end) = '9999-12-31' THEN status
ELSE 'Closed'
end
AS casestatusname
FROM tblrequesttemp AS tblrequests

SQL stored procedure with CASE

Hello i have a quation with my stored procedure , i use 2 cases here , the first case it shows me right values and its OK, the second shows me only Null values in the field TirType , i don't understand what is the problem
CREATE VIEW dbo.YUITY
SELECT CAST(dbo.SC5116.CODE AS int) AS код, dbo.SC5116.DESCR AS Наименование,
CAST(dbo.SC3420.CODE AS int) AS TIR, dbo.SC3420.SP4947 AS Date,
CASE WHEN SC3420.SP4949 <> ' 0 ' THEN 'ПовышСтрах' ELSE 'ОснСтрах' END AS VID,
CASE WHEN dbo.SC3420.SP9214 = '714' THEN '4v' END AS TirType
FROM dbo.SC3420 INNER JOIN
dbo.SC5116 ON dbo.SC3420.SP3422 = dbo.SC5116.ID
WHERE (dbo.SC3420.SP4947 <> '01.01.1753')
Don't forget END after CASE. It will return NULL if no ELSE is specified and value is not '714'.
CREATE VIEW dbo.YUITY
AS
SELECT CAST(dbo.SC5116.CODE AS int) AS код, dbo.SC5116.DESCR AS Наименование,
CAST(dbo.SC3420.CODE AS int) AS TIR, dbo.SC3420.SP4947 AS Date,
CASE WHEN SC3420.SP4949 <> ' 0 ' THEN 'ПовышСтрах' ELSE 'ОснСтрах' END AS VID,
CASE WHEN dbo.SC3420.SP9214 = '714' THEN '4v' ELSE '' END AS TirType
FROM dbo.SC3420 INNER JOIN
dbo.SC5116 ON dbo.SC3420.SP3422 = dbo.SC5116.ID
WHERE (dbo.SC3420.SP4947 <> '01.01.1753')

Concatenating multiple CASE statements into one alias

After some previous help on how to approach a problem I am having with some legacy code, it seems like the best approach for my issue is to concatenate case statements to return a value I can parse out in PHP.
I am trying to do something like this, but it is returning many rows, and eventually getting this error:
Maximum stored procedure, function, trigger, or view nesting level
exceeded (limit 32).
SELECT org.org_id,
org.org_name_1,
Datename(YEAR, member.enroll_date) AS enroll_year,
Max(CASE
WHEN board.member_from IS NULL THEN 0
ELSE 1
END) AS board_member,
CASE
WHEN ( org.delete_reason = 'OUT'
AND org.org_delete_flag = 'Y'
AND org.org_status_flag = 'C' ) THEN 'out_of_business|'
ELSE ''
END + CASE
WHEN ( stat.carrier = 'BS'
AND stat.status_id IS NOT NULL
AND stat.termination_date IS NULL
AND stat.flat_dues > 0 ) THEN 'insurance_member|'
ELSE ''
END + CASE
WHEN ( stat.carrier = 'BS'
AND stat.status_id IS NOT NULL
AND stat.termination_date IS NULL
AND stat.flat_dues = 0
AND member.status_flag IN( 'C', 'P' ) ) THEN 'insurance_product|'
ELSE ''
END + CASE
WHEN ( member.enroll_date IS NOT NULL
AND member.status_flag NOT IN( 'C', 'P' ) ) THEN 'member_since|'
ELSE ''
END + CASE
WHEN ( org.org_relationship_parent = 'Y'
AND org.dues_category = 'MBR'
AND org.org_status_flag = 'R' ) THEN 'subsidiary_member|'
ELSE ''
END + CASE
WHEN ( org.org_misc_data_9 = 'PAC' ) THEN 'pac|'
ELSE ''
END + CASE
WHEN ( org.dues_category = 'PART' ) THEN 'partner_member|'
ELSE ''
END + CASE
WHEN ( org.dues_category = 'FREE'
AND org.org_status_flag = 'P' ) THEN 'associate_member|'
ELSE ''
END
--ELSE 'non_member'
--END
AS org_status,
60 AS expires_in,
CASE
WHEN stat.dues_type = 'M' THEN
CASE
WHEN ( stat.termination_date IS NULL ) THEN ( stat.flat_dues )
ELSE 0
END
ELSE
CASE
WHEN ( member.payments = 0 ) THEN member.dues_billed_annual
ELSE member.payments
END
END AS dues_level,
CASE
WHEN ( org.affiliate_code = 'PCCE'
AND org.dues_category = 'MBR'
AND org.org_status_flag = 'R' ) THEN 1
ELSE 0
END AS pcce_membr,
-- '$'+CONVERT(VARCHAR,#dues) AS dues_level,
Ltrim(#product_level) AS product_level,
Ltrim(#involve_level) AS involvement_level
FROM organiz AS org
LEFT JOIN affilbil AS member
ON member.status_id = org.org_id
AND member.dues_category = 'MBR'
LEFT JOIN individu AS ind
ON ind.org_id = org.org_id
LEFT JOIN commembr AS board
ON board.status_id = ind.ind_id
AND board.committee_code = '5'
AND board.member_to IS NULL
LEFT JOIN statinsmorn AS stat
ON stat.status_id = org.org_id
AND stat.carrier = 'BS'
AND stat.planz = 'PCI'
WHERE org.org_id = #org_id
GROUP BY org.org_id,
org.org_name_1,
member.enroll_date,
org.delete_reason,
org.org_status_flag,
org.org_delete_flag,
stat.status_id,
stat.flat_dues,
stat.dues_type,
stat.termination_date,
org.org_misc_data_9,
org_relationship_parent,
org.dues_category,
member.status_flag,
member.dues_billed_annual,
member.payments,
stat.carrier,
org.Affiliate_Code
Well, this is embarrassing.
When I was making my changes to the stored procedure, I had inadvertently placed a call to the same procedure at the bottom. So I was recursively calling the same procedure over and over again. DOH.

"CASE" statement within "WHERE" clause in SQL Server 2008

I am working with a query which contains "CASE" statement within "WHERE" clause. But SQL Server 2008 is giving some errors while executing it. Can anyone please help me with the correct query? Here is the query:
SELECT
tl.storenum 'Store #',
co.ccnum 'FuelFirst Card #',
co.dtentered 'Date Entered',
CASE st.reasonid
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Not Active'
WHEN 0 THEN st.ccstatustypename
ELSE 'Unknown'
END 'Status',
CASE st.ccstatustypename
WHEN 'Active' THEN ' '
WHEN 'Not Active' THEN ' '
ELSE st.ccstatustypename
END 'Reason',
UPPER(REPLACE(REPLACE(co.personentered,'RT\\\\',''),'RACETRAC\\\\','')) 'Person Entered',
co.comments 'Comments or Notes'
FROM
comments co
INNER JOIN cards cc ON co.ccnum=cc.ccnum
INNER JOIN customerinfo ci ON cc.customerinfoid=ci.customerinfoid
INNER JOIN ccstatustype st ON st.ccstatustypeid=cc.ccstatustypeid
INNER JOIN customerstatus cs ON cs.customerstatuscd=ci.customerstatuscd
INNER JOIN transactionlog tl ON tl.transactionlogid=co.transactionlogid
LEFT JOIN stores s ON s.StoreNum = tl.StoreNum
WHERE
CASE LEN('TestPerson')
WHEN 0 THEN co.personentered = co.personentered
ELSE co.personentered LIKE '%TestPerson'
END
AND cc.ccnum = CASE LEN('TestFFNum')
WHEN 0 THEN cc.ccnum
ELSE 'TestFFNum'
END
AND CASE LEN('2011-01-09 11:56:29.327')
WHEN 0 THEN co.DTEntered = co.DTEntered
ELSE
CASE LEN('2012-01-09 11:56:29.327')
WHEN 0 THEN co.DTEntered >= '2011-01-09 11:56:29.327'
ELSE co.DTEntered BETWEEN '2011-01-09 11:56:29.327' AND '2012-01-09 11:56:29.327'
END
END
AND tl.storenum < 699
ORDER BY tl.StoreNum
First off, the CASE statement must be part of the expression, not the expression itself.
In other words, you can have:
WHERE co.DTEntered = CASE
WHEN LEN('blah') = 0
THEN co.DTEntered
ELSE '2011-01-01'
END
But it won't work the way you have written them eg:
WHERE
CASE LEN('TestPerson')
WHEN 0 THEN co.personentered = co.personentered
ELSE co.personentered LIKE '%TestPerson'
END
You may have better luck using combined OR statements like this:
WHERE (
(LEN('TestPerson') = 0
AND co.personentered = co.personentered
)
OR
(LEN('TestPerson') <> 0
AND co.personentered LIKE '%TestPerson')
)
Although, either way I'm not sure how great of a query plan you'll get. These types of shenanigans in a WHERE clause will often prevent the query optimizer from utilizing indexes.
Try the following:
SELECT * FROM emp_master
WHERE emp_last_name=
CASE emp_first_name
WHEN 'test' THEN 'test'
WHEN 'Mr name' THEN 'name'
END
This should solve your problem for the time being but I must remind you it isn't a good approach :
WHERE
CASE LEN('TestPerson')
WHEN 0 THEN
CASE WHEN co.personentered = co.personentered THEN 1 ELSE 0 END
ELSE
CASE WHEN co.personentered LIKE '%TestPerson' THEN 1 ELSE 0 END
END = 1
AND cc.ccnum = CASE LEN('TestFFNum')
WHEN 0 THEN cc.ccnum
ELSE 'TestFFNum'
END
AND CASE LEN('2011-01-09 11:56:29.327')
WHEN 0 THEN CASE WHEN co.DTEntered = co.DTEntered THEN 1 ELSE 0 END
ELSE
CASE LEN('2012-01-09 11:56:29.327')
WHEN 0 THEN
CASE WHEN co.DTEntered >= '2011-01-09 11:56:29.327' THEN 1 ELSE 0 END
ELSE
CASE WHEN co.DTEntered BETWEEN '2011-01-09 11:56:29.327'
AND '2012-01-09 11:56:29.327'
THEN 1 ELSE 0 END
END
END = 1
AND tl.storenum < 699
I think that the beginning of your query should look like that:
SELECT
tl.storenum [Store #],
co.ccnum [FuelFirst Card #],
co.dtentered [Date Entered],
CASE st.reasonid
WHEN 1 THEN 'Active'
WHEN 2 THEN 'Not Active'
WHEN 0 THEN st.ccstatustypename
ELSE 'Unknown'
END [Status],
CASE st.ccstatustypename
WHEN 'Active' THEN ' '
WHEN 'Not Active' THEN ' '
ELSE st.ccstatustypename
END [Reason],
UPPER(REPLACE(REPLACE(co.personentered,'RT\\\\',''),'RACETRAC\\\\','')) [Person Entered],
co.comments [Comments or Notes]
FROM comments co
INNER JOIN cards cc ON co.ccnum=cc.ccnum
INNER JOIN customerinfo ci ON cc.customerinfoid=ci.customerinfoid
INNER JOIN ccstatustype st ON st.ccstatustypeid=cc.ccstatustypeid
INNER JOIN customerstatus cs ON cs.customerstatuscd=ci.customerstatuscd
INNER JOIN transactionlog tl ON tl.transactionlogid=co.transactionlogid
LEFT JOIN stores s ON s.StoreNum = tl.StoreNum
WHERE
CASE
WHEN (LEN([TestPerson]) = 0 AND co.personentered = co.personentered) OR (LEN([TestPerson]) <> 0 AND co.personentered LIKE '%'+TestPerson) THEN 1
ELSE 0
END = 1
AND
BUT
what is in the tail is completely not understandable
There WHERE part could be written like this:
WHERE
(LEN('TestPerson') <> 0 OR co.personentered = co.personentered) AND
(LEN('TestPerson') = 0 OR co.personentered LIKE '%TestPerson') AND
(cc.ccnum = CASE LEN('TestFFNum')
WHEN 0 THEN cc.ccnum
ELSE 'TestFFNum'
END ) AND
(LEN('2011-01-09 11:56:29.327') <> 0 OR co.DTEntered = co.DTEntered ) AND
((LEN('2011-01-09 11:56:29.327') = 0 AND LEN('2012-01-09 11:56:29.327') <> 0) OR co.DTEntered >= '2011-01-09 11:56:29.327' ) AND
((LEN('2011-01-09 11:56:29.327') = 0 AND LEN('2012-01-09 11:56:29.327') = 0) OR co.DTEntered BETWEEN '2011-01-09 11:56:29.327' AND '2012-01-09 11:56:29.327' ) AND
tl.storenum < 699
select
d.DISTNAME,e.BLKNAME,a.childid,a.studyingclass
from Tbl_AdmissionRegister a
inner join District_master b on a.Schooid=b.Schooid
where
case when len('3601')=4 then c.distcd
when len('3601')=6 then c.blkcd
when len('3601')=11 then c.schcd end = '3601'
Thanks for this question, actually I am looking for something else which is in below query. this may helps someone.
SELECT DISTINCT CASE WHEN OPPORTUNITY='' THEN '(BLANK)' ELSE OPPORTUNITY END
AS OPP,LEN(OPPORTUNITY) FROM [DBO].[TBL]
above query is to fill in dropdown which blank values shows as "(blank)". Also if we pass this value into sql where clause to get blank values with other values I don't know how to handle that. And finally came up with below solution this may helps to somebody.
here it is ,
DECLARE #OPP TABLE (OPP VARCHAR(100))
INSERT INTO #OPP VALUES('(BLANK)'),('UNFUNDED'),('FUNDED/NOT COMMITTED')
SELECT DISTINCT [OPPORTUNITY]
FROM [DBO].[TBL] WHERE ( CASE WHEN OPPORTUNITY ='' THEN '(BLANK)' ELSE OPPORTUNITY END IN (SELECT OPP FROM #OPP))
ORDER BY 1
You could also try like below eg. to show only Outbound Shipments
SELECT shp_awb_no,shpr_ctry_cd, recvr_ctry_cd,
CASE WHEN shpr_ctry_cd = record_ctry_cd
THEN "O"
ELSE "I"
END AS route
FROM shipment_details
WHERE record_ctry_cd = "JP"
AND "O" = CASE WHEN shpr_ctry_cd = record_ctry_cd
THEN "O"
ELSE "I"
END
CASE LEN('TestPerson')
WHEN 0 THEN co.personentered = co.personentered ELSE co.personentered LIKE '%TestPerson'
Try the following:
... and (
(LEN('TestPerson') = 0 and co.personentered = co.personentered) or
(LEN('TestPerson') <> 0 and co.personentered LIKE '%TestPerson') ) and ...
here is my solution
AND CLI.PE_NOM Like '%' + ISNULL(#NomClient, CLI.PE_NOM) + '%'
Regads
Davy
This works
declare #v int=A
select * from Table_Name where XYZ=202
and
dbkey=(case #v when A then 'Some Value 1'
else 'Some Value 2'
end)
I'm using somtehing like that to filter users according to needle as string and a dropdown in the UI
where
u.username like '%' + isnull(#needle, '') + '%'
and 1 =
(
case
when #status = 0 then 1 -- All in uu
when #status = u.statusid then 1 -- Special status
else 0 -- otherwise reject
end
)
select TUM1.userid,TUM1.first_name + ' ' +TUM1.last_name as NAME,tum1.Business_Title,TUM1.manager_id,tum2.First_Name + ' ' + tum2.Last_Name as [MANAGER NAME],TUM1.project,TUM1.project_code,TUM1.rcc_code,TUM1.department,TCM.Company_Name,
case
when tum1.Gender_ID=1 then 'male'
else 'female'
end 'GENDER'
,tum1.Band as BAND,
case when tum1.Inactive=0 then 'STILL IN COMPANY'
else 'LEFT COMPANY'
end 'ACTIVE/INACTIVE'
from tbl_user_master TUM1
join tbl_Company_Master TCM on TCM.Company_Code=TUM1.Company_Code
join tbl_User_Master TUM2 on TUM1.Manager_ID=TUM2.UserID
where tum1.UserID in ('54545414')
SELECT * from TABLE
WHERE 1 = CASE when TABLE.col = 100 then 1
when TABLE.col = 200 then 2 else 3 END
and TABLE.col2 = 'myname';
Use in this way.

Invalid column names ERROR

i have a simple query below. but I don't know why I am getting an invalid column names error for field names and error value in where clause.
select * From (
select [SubscriberDataId]
,Case When ISNUMERIC([SubscriberCode]) = 0 Then cast([SubscriberCode]as varchar(9)) Else '~' end as [SubscriberCode]
,Case When ISDATE([Dob]) = 0 Then Cast([Dob] as Varchar(9)) Else '~' end as [Dob]
,Case When ISNUMERIC([FacetsGroup]) = 0 Then cast([FacetsGroup]as varchar(9)) Else '~' end as [FacetsGroup]
from Facets.SubscriberData) [sd]
Unpivot
(ErrorValue for FieldName in ([SubscriberCode],
[Dob],[FacetsGroup])) as x
where x.ErrorValue <> '~' and
NOT EXISTS (SELECT *
FROM Elig.dbo.ErrorTable
WHERE TableName = facets.SubscriberData
AND FieldName IN( [x].[SubscriberCode],[x].[Dob],[x].[FacetsGroup])
AND ErrorValue IN( [SubscriberCode],[Dob],[FacetsGroup]))
try
select * From
(select [SubscriberDataId],
Case When ISNUMERIC([SubscriberCode]) = 0
Then cast([SubscriberCode]as varchar(9))
Else '~' end as [SubscriberCode],
Case When ISDATE([Dob]) = 0
Then Cast([Dob] as Varchar(9))
Else '~' end as [Dob],
Case When ISNUMERIC([FacetsGroup]) = 0
Then cast([FacetsGroup]as varchar(9))
Else '~' end as [FacetsGroup]
from Facets.SubscriberData) [sd]
Unpivot (ErrorValue for FieldName in ([SubscriberCode], [Dob],[FacetsGroup])) as x where x.ErrorValue <> '~'
and NOT EXISTS (SELECT * FROM Elig.dbo.ErrorTable
WHERE TableName = facets.SubscriberData
AND FieldName IN( '[x].[SubscriberCode]','[x].[Dob]','[x].[FacetsGroup]')
AND ErrorValue IN( '[SubscriberCode]','[Dob]','[FacetsGroup]'))