Having an issue with t-sql and case statement with and/where clause - sql

SELECT 3 AS LoggedIn, 83 AS MessageID, Data AS DistID, 1 AS StatusID
, 0 AS Important
, CASE WHEN (dd.SponsorID = 3) THEN 0 ELSE d.ReceiveUplineMessages END AS Test
, dd.SponsorID
FROM msg_SplitVar(',', #MessageList) sv
INNER JOIN Distributor d
ON d.DistID = sv.Data
INNER JOIN DistributorDetail dd
ON dd.DistID = sv.Data
WHERE Data NOT IN (SELECT DistID FROM MessageBlockList WHERE BlockedID = 3)
AND Test = 0
I have a field set in the distributor table ReceiveUplineMessages. This can be set to 0 or 1.
If they set this to 0 I only want to send them a message if it is from their sponsor (logged in)
I have the case statement working, but I'm having trouble with the AND clause.
The splitVar function just takes a string based array '3,4,5,6,7' and splits the data out to individual rows for an insert statement.
Anyone know what I am doing wrong in the AND clause? I only want them to show up if ReceiveUplineMessages is a 0.

try not using your Test alias in your WHERE clause:
SELECT 3 AS LoggedIn, 83 AS MessageID, Data AS DistID, 1 AS StatusID
, 0 AS Important
, CASE WHEN (dd.SponsorID = 3) THEN 0 ELSE d.ReceiveUplineMessages END AS Test
, dd.SponsorID
FROM msg_SplitVar(',', #MessageList) sv
INNER JOIN Distributor d
ON d.DistID = sv.Data
INNER JOIN DistributorDetail dd
ON dd.DistID = sv.Data
WHERE Data NOT IN (SELECT DistID FROM MessageBlockList WHERE BlockedID = 3)
AND (CASE WHEN (dd.SponsorID = 3) THEN 0 ELSE d.ReceiveUplineMessages END) = 0
or wrap your statement in another SELECT to use your Test in the WHERE:
SELECT t.*
FROM
(
SELECT 3 AS LoggedIn, 83 AS MessageID, Data AS DistID, 1 AS StatusID
, 0 AS Important
, CASE WHEN (dd.SponsorID = 3) THEN 0 ELSE d.ReceiveUplineMessages END AS Test
, dd.SponsorID
FROM msg_SplitVar(',', #MessageList) sv
INNER JOIN Distributor d
ON d.DistID = sv.Data
INNER JOIN DistributorDetail dd
ON dd.DistID = sv.Data
WHERE Data NOT IN (SELECT DistID FROM MessageBlockList WHERE BlockedID = 3)
) t
WHERE t.Test = 0

Related

HIVESQL Query Where Statement Assistance

I have a query that I am pulling transactions from. I want to be able to pull transactions where my commodity field = A1 and the newvalue field <> A1 for any of the transactions for each individual case number. In other words, I have 2 case numbers with 5 transactions each, one case number has a transaction record of commodity = A1 and newvalue = A1. The other case has a record where commodity = A1 and newvalue= B2, this is the case I would like returned in the query. Keep in mind that the previous case may have that same transaction but it should not be returned because there is a record of newvalue = A1. I have attached an image and the records highlighted in yellow are what I expect my output to be. Below is my current "Where" statement that I need help re-writing. I was also told that I may need a "Group BY" statement which I tried and still pulled the same results.
SELECT
Allcases.caseno as caseno, Allcases.division_desc as division_desc, Allcases.close_date as close_date, Allcases.week_of as week_of,
Allcases.case_type as case_type,
a.transactdate as transactdate, a.transacttypeid as transacttypeid, a.userid as userid,
concat(RTRIM(Usr.fullname), ' <', RTRIM(Usr.EmailAddress), '>') as CR1_CR2_FULLNAME,
Allcases.commodity as commodity,
b.oldvalue as oldvalue, b.newvalue as newvalue, changereason as changereason
FROM
(
select b.*, sum(case when b.newvalue = 'A1' then 1 else 0 end) over(partition by Allcases.caseno) cnt_new_value_A1
from
dataiku.qca_casedatachange_parquet b
INNER JOIN dataiku.qcatransact_parquet a
ON b.transactid = a.transactid
INNER JOIN dataiku.qca_validated_cases_consolidated_parquet Allcases
ON a.casedataid = Allcases.casedataid
INNER JOIN dataiku.set_qca_reclassification_head_parquet h
ON Allcases.caseno = h.caseno
INNER JOIN dataiku.qca_user_parquet Usr
ON a.UserID = Usr.UserID
where
b.FieldID = 6
AND a.transacttypeid IN (1, 2, 3)
AND Allcases.commodity = 'A1'
)s
where cnt_new_value_A1 = 0
ORDER BY Allcases.caseno, A.transactid
If you do not want to return cases for which does not exists record with b.newvalue = 'A1' then calculate analytic sum() and use it in the where
select ...
from
(
select t.*,
sum(case when newvalue ='A1' then 1 else 0 end) over(partition by case_number) cnt_new_value_A1
from ...
where
FieldID = 6 --COMMODITY
AND transacttypeid IN (1, 2, 3)
AND commodity = 'A1'
)s
where cnt_new_value_A1 = 0 --No A1 in newvalue per case_number

Count Frequency based on Bit Flag

SELECT
ROW_NUMBER() OVER (PARTITION BY dicei.IsLocked ORDER BY DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded)
,DocumentInstance.PK_DocumentInstance
,DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded
,dicei.IsLocked
FROM DocumentInstance INNER JOIN
DocumentInstanceChapter ON DocumentInstance.PK_DocumentInstance = DocumentInstanceChapter.FK_DocumentInstance INNER JOIN
DocumentInstanceChapter AS DocumentInstanceChapter_1 ON
DocumentInstanceChapter.PK_DocumentInstanceChapter = DocumentInstanceChapter_1.FK_DocumentInstanceChapter INNER JOIN
DocumentInstanceChapterExpanded ON
DocumentInstanceChapter_1.PK_DocumentInstanceChapter = DocumentInstanceChapterExpanded.FK_DocumentInstanceChapter INNER JOIN
DocumentInstanceChapterExpanded AS DocumentInstanceChapterExpanded_1 ON
DocumentInstanceChapter.PK_DocumentInstanceChapter = DocumentInstanceChapterExpanded_1.FK_DocumentInstanceChapter INNER JOIN
DocumentInstanceChapterExpandedItem AS dicei ON
DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded = dicei.FK_DocumentInstanceChapterExpanded
WHERE (DocumentInstance.PK_DocumentInstance = 455)
AND DocumentInstanceChapterExpanded_1.PK_DocumentInstanceChapterExpanded = 50730
As you can see the picture what i wanted to do was add a Column which would indicate
**Result Expected**
ExpandeditemKey IsLocked StatusColumn
50797 0 Mixed
50797 0 Mixed
50797 1 Mixed
50797 1 Mixed
50797 1 Mixed
50798 1 Lock
50798 1 Lock
50798 1 Lock
If it contains 0 and 1 'Mixed'
If it contains 1 only 'Lock'
If it contains 0 only 'Unlock'
it does not necessary need to be string column, i tried using OverBy Clause if i can used Partition by for the Islock Bit Field but was not able to
Thanks for having a look.
I suggest usng MIN/MAX as window functions, then you can add a case expression that works across a partition. e.g.
SELECT
ROW_NUMBER() OVER (PARTITION BY dicei.IsLocked ORDER BY DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded)
, DocumentInstance.PK_DocumentInstance
, DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded
, dicei.IsLocked
, case when dicei.isLockedMin <> dicei.isLockedMax then 'Mixed'
when dicei.isLockedMax = 0 then 'Unlocked'
else 'Locked'
end StatusColumn
FROM DocumentInstance
INNER JOIN DocumentInstanceChapter ON DocumentInstance.PK_DocumentInstance = DocumentInstanceChapter.FK_DocumentInstance
INNER JOIN DocumentInstanceChapter AS documentinstancechapter_1 ON DocumentInstanceChapter.PK_DocumentInstanceChapter = documentinstancechapter_1.FK_DocumentInstanceChapter
INNER JOIN DocumentInstanceChapterExpanded ON documentinstancechapter_1.PK_DocumentInstanceChapter = DocumentInstanceChapterExpanded.FK_DocumentInstanceChapter
INNER JOIN DocumentInstanceChapterExpanded AS documentinstancechapterexpanded_1 ON DocumentInstanceChapter.PK_DocumentInstanceChapter = documentinstancechapterexpanded_1.FK_DocumentInstanceChapter
INNER JOIN (
select d.*
, min(d.IsLocked) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMin
, max(d.IsLocked) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMax
from DocumentInstanceChapterExpandedItem d
) AS dicei ON DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded = dicei.FK_DocumentInstanceChapterExpanded
WHERE (DocumentInstance.PK_DocumentInstance = 455)
AND documentinstancechapterexpanded_1.PK_DocumentInstanceChapterExpanded = 50730
edit, due to the bit column, case expressions were needed:
, min(case when d.IsLocked = 1 then 1 else 0 end) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMin
, max(case when d.IsLocked = 1 then 1 else 0 end) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMax

Move one reord to top

I am using SQL Server. I have the below table (marked yellow). I am in a situation to generate the output (marked green) like this.
Conditions to use in the query:
When cal_wk is 1 then target_hrs value should take from cal_wk 2
When target_hrs is empty then target_hrs should be maximum of the result
I am trying the case statement like
select
r.hour_val,
case
when us.calwk = 1
then 2
else us.calwk
end as cal_wk,
hrswk as target_hrs, u.uid
from
table1 us
inner join
users u on u.username = us.username
inner join
table2 r on u.uid = r.uid
where
us.yr = 2016
and u.uid = 2643
and r.cur_month = 7
and r.week_val = us.calwk
order by
us.calwk
This is just changing cal_wk value not target_hrs.
Could any one write a query to generate the expected_target_hrs?
Thanks in advance for your support
Try
Select
Case when calwk = 1 then wk2_max
When calwk = 0 then max
Else target_hrs end as expected_target_hours
From [table name]
Inner join
(Select max(case when calwk = 2 then target_hrs else 0 end) as wk2_max,
Max(target_hrs) as max
From [table name])
On 1 = 1
Following your update to the question, you will need to replace [table name] with that join.

multiple errors in using with function in select statement

I'm having some problems with my select statement. When I try to execute it, it gives 3 errors
Must specify table to select from
An object or column name is missing or empty for SELECT INFO statements. verify each column
has a name. For other statements, look for empty alias names. Aliases defined...
Column name or number of supplied values does not match table definition.
WITH A AS
(SELECT ROW_NUMBER() OVER (ORDER BY
CASE
WHEN #pOrderBy = 'SortByName' THEN colPortAgentVendorNameVarchar
WHEN #pOrderBy = 'SortByCOuntry' THEN colCountryNameVarchar
WHEN #pOrderBy = 'SortByCity' THEN colCityNameVarchar
END,
colPortAgentVendorNameVarchar
) xRow, A.*
FROM
(
SELECT DISTINCT
V.colPortAgentVendorIDInt,
colPortAgentVendorNameVarchar = RTRIM(LTRIM(V.colPortAgentVendorNameVarchar)),
C.colCountryNameVarchar,
Y.colCityNameVarchar,
V.colContactNoVarchar,
V.colFaxNoVarchar,
V.colEmailToVarchar,
V.colWebsiteVarchar,
BR.colBrandIdInt,
PR.colPriorityTinyint,
colBrandCodeVarchar = RTRIM(LTRIM(BR.colBrandCodeVarchar))
FROM dbo.TblVendorPortAgent V
LEFT JOIN TblCountry C ON C.colCountryIDInt = V.colCountryIDInt
LEFT JOIN TblCity Y ON Y.colCityIDInt = V.colCityIDInt
LEFT JOIN tblBrandAirportPortAgent PR ON PR.colPortAgentVendorIDInt = V.colPortAgentVendorIDInt
AND PR.colIsActiveBit = 1
LEFT JOIN TblBrand BR ON BR.colBrandIdInt = PR.colBrandIdInt
AND BR.colIsActiveBit = 1
WHERE V.colIsActiveBit = 1
AND V.colPortAgentVendorNameVarchar LIKE '%'+ #pPortAgentVendor +'%'
AND (PR.colBrandIdInt = #pBrandID OR #pBrandID = 0)
) A
)
INSERT INTO #tempPortAgent
SELECT A.*, IsWithContract = CASE WHEN colContractIdInt IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END FROM A LEFT JOIN TblContractPortAgent B ON A.colPortAgentVendorIDInt = B.colPortAgentVendorIDInt
AND B.colIsActiveBit = 1
;WITH QQ AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY Q.colPortAgentVendorIDInt ORDER BY xRow,
ContractStatusOrder,
colDateCreatedDate DESC
)ContractRow,*
FROM
(
SELECT DISTINCT GG.*, B.colContractIdInt, B.colContractStatusVarchar, B.colDateCreatedDate ,
ContractStatusOrder = CASE WHEN B.colContractStatusVarchar = 'Approved' THEN 1 ELSE '2' END
FROM #tempPortAgent GG LEFT JOIN TblContractPortAgent B ON GG.colPortAgentVendorIDInt = B.colPortAgentVendorIDInt
AND B.colIsActiveBit = 1
) Q
)SELECT * INTO #tempPortAgentWithContract
SELECT * FROM #tempPortAgentWithContract
I don't really know where its showing, because the errors are saying that these are inside the select statements inside.
1- Use Select Into instead of Insert into select
SELECT A.*, IsWithContract = CASE WHEN colContractIdInt IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END
Into #tempPortAgent
FROM A
LEFT JOIN TblContractPortAgent B ON A.colPortAgentVendorIDInt = B.colPortAgentVendorIDInt
AND B.colIsActiveBit = 1
2- SELECT * INTO #tempPortAgentWithContract is incorrect syntax. you must use following format:
SELECT * INTO #tempPortAgentWithContract From QQ

TSQL - TOP and COUNT in one SELECT

i try to combine these two statements to one, but all my tries failed!
Is it possible to merge them?
-- Is there a open answer?
SELECT CASE COUNT(tbl_Communication.pk_Communication) WHEN 0
THEN 0 ELSE 1 END AS hasAnsweredCom
FROM tbl_Communication
JOIN tbl_CommunicationElements ON tbl_CommunicationElements.pk_Communication = tbl_Communication.pk_Communication
WHERE tbl_Communication.pk_Ticket = #pk_Ticket
AND tbl_Communication.isClosed = 0
AND tbl_Communication.pk_CommunicationType = (SELECT pk_CommunicationType
FROM tbl_CommunicationType
WHERE name = 'query')
-- Get the answer text
SELECT TOP 1 tbl_Communication.subject AS hasAnsweredComStepName
FROM tbl_Communication
JOIN tbl_CommunicationElements ON tbl_CommunicationElements.pk_Communication = tbl_Communication.pk_Communication
WHERE tbl_Communication.pk_Ticket = #pk_Ticket
AND tbl_Communication.isClosed = 0
AND tbl_Communication.pk_CommunicationType = (SELECT pk_CommunicationType
FROM tbl_CommunicationType
WHERE name = 'query')
ORDER BY tbl_Communication.pk_Communication
Right join trick.
SELECT TOP 1
CASE WHEN tbl_CommunicationElements.pk_Communication IS NULL THEN 0 ELSE 1 END hasAnsweredCom
, tbl_Communication.subject AS hasAnsweredComStepName
FROM tbl_Communication
JOIN tbl_CommunicationElements ON tbl_CommunicationElements.pk_Communication = tbl_Communication.pk_Communication
RIGHT JOIN (VALUES(1)) AS Ext(x) ON (
tbl_Communication.pk_Ticket = #pk_Ticket
AND tbl_Communication.isClosed = 0
AND tbl_Communication.pk_CommunicationType = (SELECT pk_CommunicationType
FROM tbl_CommunicationType
WHERE name = 'query')
)
If you are willing to put the two results on one line, the following works:
select (CASE count(*) WHEN 0 THEN 0 ELSE 1 END) AS hasAnsweredCom,
MAX(case when seqnum = 1 then subject end) as hasAnsweredComStepName
from (SELECT tbl_Communication.pk_Communication, tbl_Communication.subject,
ROW_NUMBER() over (order by pk_communication) as seqnum
FROM tbl_Communication
JOIN tbl_CommunicationElements ON tbl_CommunicationElements.pk_Communication = tbl_Communication.pk_Communication
WHERE tbl_Communication.pk_Ticket = #pk_Ticket
AND tbl_Communication.isClosed = 0
AND tbl_Communication.pk_CommunicationType = (SELECT pk_CommunicationType
FROM tbl_CommunicationType
WHERE name = 'query')
) t
The second value will be NULL if there are no answers.
As for returning two rows. My guess is that subject is a string whereas hasAnsweredCom is an integer. The types conflict, so any sort of union or bringing the results together will probably result in a type conflict on the second row.