Multiple values in SQL CASE's THEN Statement - sql

I am wondering if it is possible to specify multiple values in the then part of a case statement in T-SQL?
I have attached a chunk of code where I am using this to join in some tables in a query. I have included a comment in the snippet.
LEFT JOIN Business B ON v.BusID = B.BusID
LEFT JOIN BusinessTypeKey T ON B.BusinessTypeID = T.BusTypeID
LEFT JOIN Location L ON L.BusID = B.BusID
AND L.HeadQuarters = CASE
WHEN (SELECT COUNT(1) from Location L2
WHERE L2.BusID = B.BusID) = 1
THEN 1,0 -- Would like to specify either 1 or 0 here. I suppose I could also make it euqal to -> L.HeadQuarters but would like a better way to impose it
ELSE 1
END

This is a little ugly, but assuming HeadQuarters is not a decimal/numeric type and only integer values,
AND L.HeadQuarters BETWEEN CASE WHEN (SELECT COUNT...) = 1 THEN 0 ELSE 1 END AND 1;

You mean...?
LEFT JOIN whatever
ON...
CASE...WHEN...THEN...END = 1
OR
CASE...WHEN...THEN...END = 0

Related

Conditionally adding a column in a SQL query

I'm trying to add a conditional SELECT column in a query and I'm having trouble writing it out:
SELECT v.GLTypeID,
v.something,
v.somethignElse,
CASE WHEN (SELECT TOP 1 Value FROM InterfaceParam WHERE InterfaceId = 0 AND Descr = 'gf') = 1 THEN a.CreditID ELSE NULL END AS CreditMemoID
FROM vGLDetails2 v
....
LEFT OUTER JOIN AssociationFund f
ON v.FundID = f.FundID
LEFT JOIN dbo.APLedger a ON v.RelID = a.APLedgerID AND v.RelTypeID IN (39, 40)
....
ORDER BY v.Code;
The query above works, however if the CASE statement is still returning an additional column regardless of the result of the subquery. How can I remove it if the subquery doesn't return a row?
How can I do this?
Change the location of AS. For example:
SELECT v.GLTypeID,
v.something,
v.somethignElse,
CASE WHEN (
SELECT TOP 1 Value
FROM InterfaceParam
WHERE InterfaceId = 0 AND Descr = 'creditMemo') = 1
THEN a.CreditID -- AS is not valid here
END AS CreditMemoID -- AS is valid here
FROM vGLDetails2 v
....
LEFT OUTER JOIN AssociationFund f
ON v.FundID = f.FundID
LEFT JOIN dbo.APLedger a ON v.RelID = a.APLedgerID AND v.RelTypeID IN (39, 40)
....
ORDER BY v.Code;
Note: I removed ELSE NULL since this is the default behavior of CASE.

WHERE Statement - Multiple conditions - adding 2 more

I can't quite get my conditions correct to alter an existing query that works.
SELECT dd.GasYear,D.DealCash_IsAgency,D.DealCash_IsNetBack, dd.GasYearName,dd.MonthName,dd.Season,dd.FirstOfMonthDate,Deal_OrigDate,DATENAME(WEEKDAY, Deal_OrigDate) AS Orig_DayofWeek
,Deal_StartDate,DATENAME(WEEKDAY, Deal_StartDate) AS Start_DayofWeek,Deal_StopDate,DATENAME(WEEKDAY, Deal_StopDate) AS Stop_DayofWeek
,CASE
WHEN CAST(DATEDIFF(d, Deal_StartDate, Deal_StopDate) AS CHAR(10)) > 6 THEN 'All Other'
END AS DealType
,Deal_Owner,d.Deal_Id,CP_Cmp_ShortName
,CASE
WHEN Qty_MeasurementType_Short = 'GJ' THEN DealCashTran_Qty / 2.055098
ELSE DealCashTran_Qty
END DealCashTran_Dth_Qty
FROM uvDealCash d
LEFT OUTER JOIN uvDealCashTran AS dct
ON d.Deal_Id = dct.Deal_Id
INNER JOIN Cmp c
ON d.CP_Cmp_ShortName = c.Cmp_ShortName
INNER JOIN [uvCmp_CmpType_CmpCPType] ct
ON c.Cmp_Id = ct.Cmp_Id
INNER JOIN BISandbox.dbo.dimDate dd
ON d.Deal_StartDate = dd.FullDate
WHERE ((Deal_Owner IN ('TYK', 'JTT', 'MML', 'CGG', 'LIO', 'MAT')
AND ct.CmpCPType_Descript = 'Producer')
--US Entities Kristen's wants added
OR (CP_Cmp_ShortName IN ('SEV', 'CNAT', 'TNMKT', 'CENT')))
AND Deal_LengthInMonths >= 0
AND DATEDIFF(d, Deal_StartDate, Deal_StopDate) > 6
AND Deal_StartDate > '4/1/2018' --=<Parameters.StartDate>
AND DealPurchaseSellType_Short = 'P'
AND d.DealCashType_Short IN ('DFM', 'FM')
In addition to the above I want to exclude results if DealCash_IsAgency = 1 or D.DealCash_IsNetBack = 1
I tried several variations by adding this to the end of the existing WHERE statement.
--exclude AMA and NB
AND (D.DealCash_IsAgency = 1 OR D.DealCash_IsNetBack = 1)
It still returns rows with 1's in both of the columns.
Greatly appreciate any suggestions.
Thanks
Brent
if you want to exclude then you have to add a condition like this by adding not:
AND NOT (D.DealCash_IsAgency = 1 OR D.DealCash_IsNetBack = 1)

SQL avoid 0 in the calculation

Can anyone help me try to solve this equation? The "Lost_Weight" is a calculation field and I'm trying to get the result of HWeight - renWeight = '0' if the renWeight is 0. The where clause has a controversial statement that put a Challenge to me to make that happen. See below.
SELECT TOP (100) PERCENT dbo.Name.ID,
dbo.Name.CO_ID,
dbo.Name.FULL_NAME,
dbo.Name.STATE_PROVINCE, dbo.Tops_Profile.START_WGHT,
dbo.Tops_Profile.RENEWAL_WEIGHT,
dbo.Tops_Profile.H_WEIGHT - dbo.Tops_Profile.RENEWAL_WEIGHT AS Lost_Weight,
dbo.Tops_Profile.H_WEIGHT,
dbo.Name.JOIN_DATE,
dbo.Name.BIRTH_DATE,
RIGHT(dbo.TOPS_AWARDS.AWARD_TYPE, 15) AS AWARDS_TYPE,
dbo.TOPS_AWARDS.AWARD_CATEGORY,
dbo.TOPS_AWARDS.AWARD_DATE,
dbo.vw_RegDirs.TARGET_ID AS
RD_ID,
dbo.vw_Coords.TARGET_ID AS Coord_ID,
dbo.vw_Coords.FULL_NAME AS
Coord_Name,
dbo.vw_AreaCapts.TARGET_ID AS AC_ID, dbo.Name.STATUS
FROM dbo.Name INNER JOIN dbo.Tops_Profile
ON dbo.Name.ID = dbo.Tops_Profile.ID
INNER JOIN dbo.vw_RegDirs
ON dbo.Name.CO_ID = dbo.vw_RegDirs.CHAPTER
INNER JOIN dbo.vw_Coords
ON dbo.Name.CO_ID = dbo.vw_Coords.CHAPTER
INNER JOIN dbo.vw_AreaCapts
ON dbo.Name.CO_ID = dbo.vw_AreaCapts.CHAPTER
LEFT OUTER JOIN dbo.TOPS_AWARDS
ON dbo.Name.ID = dbo.TOPS_AWARDS.ID
WHERE (dbo.Tops_Profile.RENEWAL_WEIGHT <> '0')
AND (dbo.Name.STATUS = 'a')
AND (dbo.Tops_Profile.H_WEIGHT - dbo.Tops_Profile.RENEWAL_WEIGHT >= 100')
OR (dbo.Name.STATUS = 'a') AND (dbo.TOPS_AWARDS.AWARD_TYPE LIKE '%Century%')
right now if the renewal_weight is 0 it automatically give me the number from the H_WEIGHT in the Lost_Weight field and I need the result to be 0 if the RENEWAL_WEIGHT is 0.
I'm guessing 0 is a special value in this situation. This can be fixed by using CASE
Replace
dbo.Tops_Profile.H_WEIGHT - dbo.Tops_Profile.RENEWAL_WEIGHT AS Lost_Weight
With
CASE WHEN RENEWAL_WEIGHT = 0 THEN 0
ELSE dbo.Tops_Profile.H_WEIGHT - dbo.Tops_Profile.RENEWAL_WEIGHT
END AS Lost_Weight

How can I refactor this query

How can I rewrite this SQL code? I would like to avoid the repetitive execution of the case for every record.
SELECT chcr.chsid,
CASE
WHEN EXISTS
(SELECT 1
FROM hdr_run chre,
clmerr ce
WHERE chre.chsid = chcr.chsid
AND chre.run_nmbr < chcr.last_run_nmbr
AND chre.clm_error_sid = ce.clm_error_sid
GROUP BY chre.chsid
HAVING COUNT(chre.clm_error_sid) > 0
)
THEN 'Appended'
ELSE 'Never Appended'
END Run_Detail
FROM
clm_res chcr,
clm_der chde
WHERE chde.chsid = chcr.chsid
Have a look at that query please:
SELECT
chcr.chsid,
CASE
WHEN ce.clm_error_sid IS NOT NULL AND COUNT(chre.clm_error_sid, 0) > 0
THEN 'Appended'
ELSE 'Never Appended'
END Run_Detail
FROM
clm_res chcr
JOIN clm_der chde ON chde.chsid = chcr.chsid
LEFT JOIN hdr_run chre ON chre.chsid = chcr.chsid AND chre.run_nmbr < chcr.last_run_nmbr
LEFT JOIN clmerr ce ON chre.clm_error_sid = ce.clm_error_sid
GROUP BY chcr.chsid
If there's more than one clm_der for each clm_res based on their chsid, we'd have to double check that the COUNT is not counting the extras from clm_der.
I have no data to test this on so all I can go on is the SQL you've provided but from a brief look it does not appear that the GROUP BY and HAVING COUNT() > 0 statements are required as the combination of the INNER JOIN condition in the sub-query and the use of EXISTS in the outer query does the same thing.
Does this have exactly the same functionality:
SELECT chcr.chsid,
CASE
WHEN EXISTS
( SELECT 1
FROM hdr_run chre
INNER JOIN
clmerr ce
ON (chre.clm_error_sid = ce.clm_error_sid)
WHERE chre.chsid = chcr.chsid
AND chre.run_nmbr < chcr.last_run_nmbr
)
THEN 'Appended'
ELSE 'Never Appended'
END Run_Detail
FROM clm_res chcr
INNER JOIN
clm_der chde
ON ( chde.chsid = chcr.chsid );
SQLFIDDLE
Also, repeated execution of the CASE statement is not a bad thing as the optimizer should not duplicate executions of the sub-query.

Is it possible to get several COUNT in one single SQL request?

I need help to write a simple procedure. Let me explain what I'm trying to do.
I have 3 tables
tJobOffer
tApplication
tApplicationStatus
I would like to create a procedure that return me a list of tJobOffer with the statistics of different status of this tJobOffer. tApplicationStatus is linked to tApplication that is linked to tJobOffer. An application can be CANDIDATE / ACCEPTED / REFUSED / IGNORED / ...
I created this query :
SELECT
[T].[JobOfferId],
[T].[JobOfferTitle],
COUNT([A].[ApplicationId]) AS [CandidateCount]
FROM [tJobOffer] AS [T]
LEFT JOIN [tApplication] AS [A]
INNER JOIN [tApplicationStatus] AS [S]
ON [S].[ApplicationStatusId] = [A].[ApplicationStatusId]
AND [S].[ApplicationStatusTechnicalName] = 'CANDIDATE'
ON [A].[JobOfferId] = [T].[JobOfferId]
GROUP BY
[T].[JobOfferId],
[T].[JobOfferTitle]
ORDER BY [T].[JobOfferTitle] ;
The result is
> 52ED7C67-21E1-49BB-A1F8-0601E6EED1EA Announce a 0
> F26B228D-0C81-4DA8-A287-F8F997CC1F9C Announce b 0
> 9DA60B23-F113-4C7F-9707-2B90C1556D5D Announce c 2
> 258E11A7-79C1-47B6-8C61-413AA54E2360 Announce d 0
> DA582383-5DF4-4E1D-837C-382371BDEF57 Announce e 1
The result is correct. I get my tJoboffers with statistic on status candidate. I have 2 candidates for Announce c and 1 candidate for announce e. If I change my string 'CANDIDATE' to 'ACCEPTED' or 'REFUSED' I can get the statistic on these status. Is it possible to get everything in one request?
Something like
> 52ED7C67-21E1-49BB-A1F8-0601E6EED1EA Announce a 0 0 2
> F26B228D-0C81-4DA8-A287-F8F997CC1F9C Announce b 0 0 1
> 9DA60B23-F113-4C7F-9707-2B90C1556D5D Announce c 2 0 0
> 258E11A7-79C1-47B6-8C61-413AA54E2360 Announce d 0 0 0
> DA582383-5DF4-4E1D-837C-382371BDEF57 Announce e 1 1 0
use SUM and CASE
SELECT
[T].[JobOfferId],
[T].[JobOfferTitle],
SUM(CASE WHEN [S].[ApplicationStatusTechnicalName] = 'CANDIDATE' THEN 1 ELSE 0 END) AS [CandidateCount],
SUM(CASE WHEN [S].[ApplicationStatusTechnicalName] = 'ACCEPTED' THEN 1 ELSE 0 END) AS [ACCEPTEDCount],
SUM(CASE WHEN [S].[ApplicationStatusTechnicalName] = 'REFUSED' THEN 1 ELSE 0 END) AS [REFUSEDCount]
FROM [tJobOffer] AS [T]
LEFT JOIN [tApplication] AS [A]
ON [A].[JobOfferId] = [T].[JobOfferId]
LEFT JOIN [tApplicationStatus] AS [S]
ON [S].[ApplicationStatusId] = [A].[ApplicationStatusId]
GROUP BY
[T].[JobOfferId],
[T].[JobOfferTitle]
ORDER BY [T].[JobOfferTitle] ;
Yes, it is. One way to do that is to use the PIVOT function. The other way to do this would be to use LEFT OUTER JOIN each time you need a count of items, something like that:
SELECT a.JobID, COUNT(b.JobID), COUNT(c.JobID)
FROM AllVacancies as a
LEFT OUTER JOIN
(SELECT JobID from AllVacancies WHERE ApplicationStatus = 'CANDIDATE') as b
ON a.JobID = b.JobID
LEFT OUTER JOIN
(SELECT JobID FROM AllVacancies WHERE ApplicationStatus = 'ACCEPTED') as c
ON a.JobID = cJobID
as many times as the categories that you need.
Yes you can carry as many counts as you want
try this
SELECT COUNT(1),COUNT(2) FROM demoTable;
this will give you the count of no of rows in column 1 and column two
usually this will result the same count unless you have any null values allowesd and existing in any of the column.
If any column has any null value then its count may differ , so basically the idea is to apply count on the primary Key column .
Select count(*) from demoTable ;
this line also results in count values but it applies for the complete table , so performance wise applying count on any particular column is better .
again on the accuracy issue this must be applied on the column with primary key or not null constraint .
moving further , you need not to restrain to a single table
SELECT COUNT(1),COUNT(2) FROM ( joins or any selection from any no of table);
just be aware of the no of columns existing in the selection set