Lexicographical comparison in SQL SERVER - sql-server

I have to execute queries to select rows where the composite key is lexicographically less than or greater than some given tuple of values:
SELECT TOP 100
*
FROM PALISBSD
WHERE (recbsd_key_bsd_key_bsd1_bsd_jar < '03'
OR (recbsd_key_bsd_key_bsd1_bsd_jar = '03'
AND (recbsd_key_bsd_key_bsd1_bsd_pro < 'L'
OR (recbsd_key_bsd_key_bsd1_bsd_pro = 'L'
AND (recbsd_key_bsd_key_bsd1_bsd_az1_bsd_kst < 'C'
OR (recbsd_key_bsd_key_bsd1_bsd_az1_bsd_kst = 'C'
AND (recbsd_key_bsd_key_bsd1_bsd_az1_bsd_azl < '00017004'
OR (recbsd_key_bsd_key_bsd1_bsd_az1_bsd_azl = '00017004'
AND (recbsd_key_bsd_key_bsd1_bsd_linr < '0001'
OR (recbsd_key_bsd_key_bsd1_bsd_linr = '0001'
AND (recbsd_key_bsd_key_bsd1r_bsd_sa < 'D'
OR (recbsd_key_bsd_key_bsd1r_bsd_sa = 'D'
AND (recbsd_key_bsd_key_bsd1r_bsd_an < 'PTZ')))))))))))))
ORDER BY recbsd_key_bsd_key_bsd1_bsd_jar DESC,
recbsd_key_bsd_key_bsd1_bsd_pro DESC,
recbsd_key_bsd_key_bsd1_bsd_az1_bsd_kst DESC,
recbsd_key_bsd_key_bsd1_bsd_az1_bsd_azl DESC,
recbsd_key_bsd_key_bsd1_bsd_linr DESC,
recbsd_key_bsd_key_bsd1r_bsd_sa DESC,
recbsd_key_bsd_key_bsd1r_bsd_an DESC;
A clustered index exists that contains all the columns named here, in exactly this order. However its often not used to perform a seek. In fact I can accelerate a lot, but not all of my queries by providing the WITH (FORCESEEK) hint or by prefixing the where term with something like recbsd_key_bsd_key_bsd1_bsd_jar <= '03' AND.
My question is: Is there a better way to express lexicographical comparison, so MS SQL Server will better utilize the indices for the comparison? In Postgres this would be expressed via tuple comparison (col1, col2) < ('FOO', 'BAR'), but no such feature exists in MS SQL Server.
Edit: I cannot create a concatenated computed column, because the key might contain non-character fields as well.

Using Statements instead of PreparedStatements and rearranging the filter to look like the following, as opposed to the form in my question, actually seems to make SQL Server use the index:
SELECT TOP 100 * FROM PALISBSD
WHERE
(recbsd_key_bsd_key_bsd1_bsd_jar < '03') OR
(recbsd_key_bsd_key_bsd1_bsd_jar = '03' AND recbsd_key_bsd_key_bsd1_bsd_pro < 'L') OR
(recbsd_key_bsd_key_bsd1_bsd_jar = '03' AND recbsd_key_bsd_key_bsd1_bsd_pro = 'L' AND recbsd_key_bsd_key_bsd1_bsd_az1_bsd_kst < 'C') OR
(recbsd_key_bsd_key_bsd1_bsd_jar = '03' AND recbsd_key_bsd_key_bsd1_bsd_pro = 'L' AND recbsd_key_bsd_key_bsd1_bsd_az1_bsd_kst = 'C' AND recbsd_key_bsd_key_bsd1_bsd_az1_bsd_azl < '00017004') OR
(recbsd_key_bsd_key_bsd1_bsd_jar = '03' AND recbsd_key_bsd_key_bsd1_bsd_pro = 'L' AND recbsd_key_bsd_key_bsd1_bsd_az1_bsd_kst = 'C' AND recbsd_key_bsd_key_bsd1_bsd_az1_bsd_azl = '00017004' AND recbsd_key_bsd_key_bsd1_bsd_linr < '0001') OR
(recbsd_key_bsd_key_bsd1_bsd_jar = '03' AND recbsd_key_bsd_key_bsd1_bsd_pro = 'L' AND recbsd_key_bsd_key_bsd1_bsd_az1_bsd_kst = 'C' AND recbsd_key_bsd_key_bsd1_bsd_az1_bsd_azl = '00017004' AND recbsd_key_bsd_key_bsd1_bsd_linr = '0001' AND recbsd_key_bsd_key_bsd1r_bsd_sa < 'D') OR
(recbsd_key_bsd_key_bsd1_bsd_jar = '03' AND recbsd_key_bsd_key_bsd1_bsd_pro = 'L' AND recbsd_key_bsd_key_bsd1_bsd_az1_bsd_kst = 'C' AND recbsd_key_bsd_key_bsd1_bsd_az1_bsd_azl = '00017004' AND recbsd_key_bsd_key_bsd1_bsd_linr = '0001' AND recbsd_key_bsd_key_bsd1r_bsd_sa = 'D' AND recbsd_key_bsd_key_bsd1r_bsd_an < 'PTZ')
ORDER BY
recbsd_key_bsd_key_bsd1_bsd_jar DESC,
recbsd_key_bsd_key_bsd1_bsd_pro DESC,
recbsd_key_bsd_key_bsd1_bsd_az1_bsd_kst DESC,
recbsd_key_bsd_key_bsd1_bsd_az1_bsd_azl DESC,
recbsd_key_bsd_key_bsd1_bsd_linr DESC,
recbsd_key_bsd_key_bsd1r_bsd_sa DESC,
recbsd_key_bsd_key_bsd1r_bsd_an DESC;
I am aware of SQL Injections and I'm preventing them in other ways.

Related

How can I show these 3 query result in one table in SSMS?

WHILE #i <= #stsem
BEGIN
SELECT
SUM(sb.totalmarks) AS Sub_total,
SUM(sb.credit) AS Credit_total,
SUM(a.totalmarks) AS Total_obt,
SUM(a.rankpoint) AS RP_total,
(SUM(rankpoint) / SUM(sb.credit)) AS SGPA,
#i AS Sem
FROM
umms.dbo.[dt_result] AS a
JOIN
umms.dbo.[dt_subjectdetails] AS sb ON a.paperid = sb.paperid
WHERE
studentid = 17780
AND btid = 495
AND a.semid = #i
AND (grade != 'F' OR grade != 'Ab' OR grade != 'IN')
IF #i = 10
BREAK;
SET #i = #i + 1;
END;
SELECT SUM(b.credit) as TotalCredit,SUM(rankpoint) as TotalGradepoint ,(SUM(rankpoint)/SUM(b.credit)) as CGPA FROM umms.dbo.[dt_result] as a join umms.dbo.[dt_subjectdetails] as b on a.paperid=b.paperid where studentid=17780 and btid=495
This query executes 3 times.
It seems a simple filter on a.semid and a GROUP BY on the same column should do the trick:
SELECT
SUM(sb.totalmarks) AS Sub_total,
SUM(sb.credit) AS Credit_total,
SUM(a.totalmarks) AS Total_obt,
SUM(a.rankpoint) AS RP_total,
(SUM(rankpoint) / SUM(sb.credit)) AS SGPA,
a.semid AS Sem
FROM
umms.dbo.[dt_result] AS a
JOIN
umms.dbo.[dt_subjectdetails] AS sb ON a.paperid = sb.paperid
WHERE
studentid = 17780
AND btid = 495
AND a.semid >= 1 AND a.semid <= 10
AND (grade != 'F' OR grade != 'Ab' OR grade != 'IN')
GROUP BY
a.semid;
The second query could potentially be combined also, by using a ROLLUP, but the grade and semid filters make this more difficult.
The logic grade != 'F' OR grade != 'Ab' OR grade != 'IN' appears incorrect. I suggest you take a look at it.
You don't seem to need a loop here, try this instead
;WITH CTE
AS
(
SELECT
RN = 1
UNION ALL
SELECT
RN = RN +1
FROM CTE
WHERE RN <10
)
SELECT
SUM(sb.totalmarks) AS Sub_total,
SUM(sb.credit) AS Credit_total,
SUM(a.totalmarks) AS Total_obt,
SUM(a.rankpoint) AS RP_total,
(SUM(rankpoint) / SUM(sb.credit)) AS SGPA,
CTE.RN AS Sem
FROM
umms.dbo.[dt_result] AS a
JOIN
umms.dbo.[dt_subjectdetails] AS sb ON a.paperid = sb.paperid
JOIN CTE
ON a.semid = CTE.RN
WHERE
studentid = 17780
AND btid = 495
AND (grade != 'F' OR grade != 'Ab' OR grade != 'IN')
GROUP BY
CTE.RN

How to get a windowed function working in WHERE clause

I know that there are quite many threads on "Windowed functions can only appear in the select or ORDER BY clases" topic, but I have read them through and just don't seem to get any of those trick to work for me. So here I go.
My Query you can see below the line. I have highlighted the part of the Query which is "causing" me issues or problems. The thing is that I would like to get
"LocalCurrentAmount not between -1.000000 and 1.000000"
in somehow. I have tried the CTE versioon, but somehow didn't work and my declare tables and then the details view started causing problems.
Would really appreciate your help!
Jaanis
declare #exceptions1 table (CustomerCode varchar(7), Exception_comment varchar(15));
insert into #exceptions1 (CustomerCode, Exception_comment)
VALUES
(3514437,'Exception'),(3500977,'Exception'),(3295142,'Exception'), ...
declare #exceptions2 table (CustomerCode2 varchar(7), Exception_comment2 varchar(15));
insert into #exceptions2 (CustomerCode2, Exception_comment2)
VALUES
(3390437,'VIP SE') ,(3390438,'VIP SE') ,(3390481,'VIP SE'), ...
declare #exceptions3 table (CustomerCode3 varchar(7), Exception_comment3 varchar(15));
insert into #exceptions1 (CustomerCode, Exception_comment)
VALUES
(1530350, 'DK Exception'), (1533834, 'DK Exception'), (1530002, 'DK Exception'), ...
with Details as
(
select ard.AccountsReceivableHeaderID, sum(ard.TransactionAmountOC) as DetailAmountOC , Max(DetailSequenceCode) as DetailSequenceCode, Max( ard.BatchDate) as BatchDate
from dmbase.fAccountsReceivableDetail ard
join dmbase.fAccountsReceivable arh on ard.AccountsReceivableHeaderID = arh.AccountsReceivableID
where ard.BatchDate <= getdate()
group by AccountsReceivableHeaderID
)
SELECT
comp.CompanyCode
,convert(varchar(10),ar.InvoiceDate, 103) as Invoice_date -- dd/MM/yyyy format
,case
when ar.IsCreditMemo = 'Y' then 'Memo (Credit/Debit)'
when ar.InvoiceCode = '0' then 'Payment'
else 'Invoice'
end as Description
,isnull(cm.SummaryInvoiceCode, ar.InvoiceSummaryCode) InvoiceSummaryCode
,case
when len(ar.InvoiceSequenceCode) = '1' then CONCAT(ar.InvoiceCode,'-000',ar.InvoiceSequenceCode)
when len(ar.InvoiceSequenceCode) = '2' then CONCAT(ar.InvoiceCode,'-00',ar.InvoiceSequenceCode)
when len(ar.InvoiceSequenceCode) = '3' then CONCAT(ar.InvoiceCode,'-0',ar.InvoiceSequenceCode)
else CONCAT(ar.InvoiceCode,'-',ar.InvoiceSequenceCode)
end as Invoice#
,**(ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end
+
coalesce(det.DetailAmountOC, 0)) * coalesce(cer.CurrencyExchangeRate, ar.CurrencyExchangeRate) AS LocalCurrentAmount**
,(ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end
+ coalesce(det.DetailAmountOC, 0)) AS CurrentAmount
,ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end as OriginalInvoiceAmountOC
,ar.InvoiceCurrencyCode
,cust.CustomerCode
,upper(cust.CustomerName) as CustomerName
from
dmbase.fAccountsReceivable ar
INNER JOIN dmbase.dlocation loc
ON loc.LocationID = ar.LocationID
INNER JOIN dmbase.dCustomer cust
ON cust.CustomerID = ar.CustomerID
LEFT JOIN dmbase.VatAdjustment vat
on ar.InvoiceCode = vat.contractNumber
and ar.InvoiceSequenceCode = vat.invoiceSequence
and cust.CustomerCode = vat.CustomerNumber
and loc.CompanyCode = vat.companyCode
inner join dmbase.dCompany comp
on (ar.CompanyID = comp.CompanyID)
left join dmbase.dAccountsReceivableInvoiceStatus aris
on (aris.ARInvoiceStatusAMID=ar.ARInvoiceStatusAMID)
left hash join Details det
on (ar.AccountsReceivableID = det.AccountsReceivableHeaderID)
left join dmbase.dCurrencyExchangeRate cer
on (comp.CompanyCode = cer.CompanyCode
and ar.InvoiceCurrencyCode = cer.CurrencyCode
and case ar.InvoiceDate when '1900-01-01' then getdate() else ar.InvoiceDate end between cer.ValidFrom and cer.ValidTo)
left join dmbase.fContractClosedHeader ccd
on ccd.ContractNumber = ar.InvoiceCode
and ccd.ContractSeqNumber = ar.InvoiceSequenceCode
and ccd.CompanyID = ar.CompanyID
and ccd.ContractNumber!='0'
and ccd.CreditMemoContractNumber != '0'
left join dmbase.fAccountsReceivableHeader cm
on ccd.CreditMemoContractNumber = cm.ContractNumber
and ccd.CreditMemoSequenceCode = cm.ContractSeqNumber
and cm.CompanyID = ccd.CompanyID
where
(aris.ARInvoiceStatusCode = 'OP' or (ar.LastPaymentDate >= getdate())
or (ar.TotalAdjustmentsAmountOC <> 0 and ar.CurrentAmountLC = 0
and (ar.OriginalInvoiceAmountOC + isnull(vat.vatAdjustment, 0) ) + coalesce(det.DetailAmountOC, 0) <> 0)
)
and ar.OriginalInvoiceAmountOC <= 0
and ar.IsCreditMemo = 'Y' -- ainult Memo (Credit/Debit)
and cust.InternalCustomerType = 'External'
and cust.CustomerName not in ('RR AJM', 'RAMIRENT', 'Ramirent')
and cust.CustomerName not like '%[7][0-9][0-9][0-9]%'
and ar.InvoiceDate <= EOMONTH(getdate(),-3
and cust.CustomerCode NOT IN
(select CustomerCode from #exceptions1
union
select CustomerCode2 from #exceptions2
union
select CustomerCode3 from #exceptions3)
order by Invoice_date
When using a Window function, like you said in your post, you can't use it in the WHERE clause. The common solution, therefore, is to use a CTE and reference it in the WHERE outside of it. I've used your CTE, however, without any kind of sample data this is a total guess. I've also left a lot of comments for you, and changed some other parts of the SQL, as some of the clauses you have will effect your query's performance.
WITH
Details AS
(SELECT ard.AccountsReceivableHeaderID,
SUM(ard.TransactionAmountOC) AS DetailAmountOC,
MAX(DetailSequenceCode) AS DetailSequenceCode,
MAX(ard.BatchDate) AS BatchDate
FROM dmbase.fAccountsReceivableDetail ard
JOIN dmbase.fAccountsReceivable arh ON ard.AccountsReceivableHeaderID = arh.AccountsReceivableID
WHERE ard.BatchDate <= GETDATE()
GROUP BY AccountsReceivableHeaderID),
Summary AS(
SELECT comp.CompanyCode,
CONVERT(varchar(10), ar.InvoiceDate, 103) AS Invoice_date, -- dd/MM/yyyy format
CASE
WHEN ar.IsCreditMemo = 'Y' THEN 'Memo (Credit/Debit)'
WHEN ar.InvoiceCode = '0' THEN 'Payment'
ELSE 'Invoice'
END AS Description,
ISNULL(cm.SummaryInvoiceCode, ar.InvoiceSummaryCode) AS InvoiceSummaryCode,
CASE
WHEN LEN(ar.InvoiceSequenceCode) = '1' THEN CONCAT(ar.InvoiceCode, '-000', ar.InvoiceSequenceCode)
WHEN LEN(ar.InvoiceSequenceCode) = '2' THEN CONCAT(ar.InvoiceCode, '-00', ar.InvoiceSequenceCode)
WHEN LEN(ar.InvoiceSequenceCode) = '3' THEN CONCAT(ar.InvoiceCode, '-0', ar.InvoiceSequenceCode)
ELSE CONCAT(ar.InvoiceCode, '-', ar.InvoiceSequenceCode)
END AS Invoice#,
(ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END + COALESCE(det.DetailAmountOC, 0)) * COALESCE(cer.CurrencyExchangeRate, ar.CurrencyExchangeRate) AS LocalCurrentAmount,
(ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END + COALESCE(det.DetailAmountOC, 0)) AS CurrentAmount,
ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END AS OriginalInvoiceAmountOC,
ar.InvoiceCurrencyCode,
cust.CustomerCode,
UPPER(cust.CustomerName) AS CustomerName
FROM dmbase.fAccountsReceivable ar
INNER JOIN dmbase.dlocation loc ON loc.LocationID = ar.LocationID
INNER JOIN dmbase.dCustomer cust ON cust.CustomerID = ar.CustomerID
LEFT JOIN dmbase.VatAdjustment vat ON ar.InvoiceCode = vat.contractNumber
AND ar.InvoiceSequenceCode = vat.invoiceSequence
AND cust.CustomerCode = vat.CustomerNumber
AND loc.CompanyCode = vat.companyCode
INNER JOIN dmbase.dCompany comp ON (ar.CompanyID = comp.CompanyID)
LEFT JOIN dmbase.dAccountsReceivableInvoiceStatus aris ON (aris.ARInvoiceStatusAMID = ar.ARInvoiceStatusAMID)
LEFT HASH JOIN Details det ON (ar.AccountsReceivableID = det.AccountsReceivableHeaderID)
LEFT JOIN dmbase.dCurrencyExchangeRate cer ON (comp.CompanyCode = cer.CompanyCode
AND ar.InvoiceCurrencyCode = cer.CurrencyCode
AND CASE ar.InvoiceDate WHEN '1900-01-01' THEN GETDATE()ELSE ar.InvoiceDate END BETWEEN cer.ValidFrom AND cer.ValidTo)
LEFT JOIN dmbase.fContractClosedHeader ccd ON ccd.ContractNumber = ar.InvoiceCode
AND ccd.ContractSeqNumber = ar.InvoiceSequenceCode
AND ccd.CompanyID = ar.CompanyID
AND ccd.ContractNumber != '0'
AND ccd.CreditMemoContractNumber != '0'
LEFT JOIN dmbase.fAccountsReceivableHeader cm ON ccd.CreditMemoContractNumber = cm.ContractNumber
AND ccd.CreditMemoSequenceCode = cm.ContractSeqNumber
AND cm.CompanyID = ccd.CompanyID
WHERE (aris.ARInvoiceStatusCode = 'OP'
OR (ar.LastPaymentDate >= GETDATE())
OR (ar.TotalAdjustmentsAmountOC <> 0
AND ar.CurrentAmountLC = 0
AND (ar.OriginalInvoiceAmountOC + ISNULL(vat.vatAdjustment, 0)) + COALESCE(det.DetailAmountOC, 0) <> 0)) --Why ISNULL for one, COALESCE for the other? Both will make the query non-SARGable
AND ar.OriginalInvoiceAmountOC <= 0
AND ar.IsCreditMemo = 'Y' -- ainult Memo (Credit/Debit)
AND cust.InternalCustomerType = 'External'
AND cust.CustomerName NOT IN ('RR AJM', 'RAMIRENT', 'Ramirent')
AND cust.CustomerName NOT LIKE '%[7][0-9][0-9][0-9]%' --A leading wildcard is going to perform slow
AND ar.InvoiceDate <= EOMONTH(DATEADD(DAY, -3, GETDATE())) --I have changed this from EOMONTH(GETDATE(), -3 (which made no sense)
AND NOT EXISTS (SELECT 1
FROM #exceptions1 E
WHERE E.CustomerCode = cust.CustomerCode) --Changed to EXISTS binned UNION you should use UNION ALL if you're doing something like this, it'll be quicker)
AND NOT EXISTS (SELECT 1
FROM #exceptions2 E
WHERE E.CustomerCode = cust.CustomerCode) --Changed to EXISTS binned UNION (you should use UNION ALL if you're doing something like this, it'll be quicker)
AND NOT EXISTS (SELECT 1
FROM #exceptions3 E
WHERE E.CustomerCode = cust.CustomerCode)) --Changed to EXISTS binned UNION you should use UNION ALL if you're doing something like this, it'll be quicker)
SELECT *
FROM Summary
WHERE LocalCurrentAmount NOT BETWEEN -1 AND 1
ORDER BY Invoice_date;
It's worth noting that the above sql is completely untested. I do not have access to your server, or data, so I'm purely relying on "my eye" to note any errors.

PySpark: Translating MSSQL Code w/Inner Joins, Case Statements, and Where Statements

I'm trying to replicate code that I wrote in MSSQL and translate it to PySpark. I'm a noob at PySpark.
The query contains inner joins, embedded case when statements and a bunch of where statements for filtering.
SELECT Table1.Part, Table1.Serial, Table1.AIRCRAFT_NUMBER, Table1.date_removed,
Table2.dbo.E15.TIME, Table2.dbo.E15.TSO, data.dbo.EE18.Allowable_Time,
CASE WHEN (data.dbo.EE18.Allowable_Time > 0)
THEN data.dbo.EE18.Allowable_Time - Table2.dbo.E15.TSO END AS CAL
FROM Table1 INNER JOIN
Table2.dbo.E15 ON Table1.SEQ_ID = Table2.dbo.E15.SEQ_ID AND
Table1.Part = Table2.dbo.E15.Part AND
Table1.Serial = Table2.dbo.E15.Serial AND
Table1.DATE_REMOVED_DESCENDING = Table2.dbo.E15.DATE_REMOVED_DESCENDING INNER JOIN
data.dbo.EE18 ON Table2.dbo.E15.Part = data.dbo.EE18.PART_NUMBER AND
Table2.dbo.E15.TIME = data.dbo.EE18.TIME
WHERE (Table1.Part LIKE '18%') AND (Table2.dbo.E15.TIME = 'I') AND
(data.dbo.EE18.Allowable_Time > 0) AND (Table2.dbo.E15.TSO <= 2) OR
(Table1.Part LIKE '18%') AND (Table2.dbo.E15.TIME = 'T') AND
(data.dbo.EE18.Allowable_Time > 0) AND (Table2.dbo.E15.TSO <= 20) OR
(Table1.Part LIKE '18%') AND (Table2.dbo.E15.TIME = 'L') AND
(data.dbo.EE18.Allowable_Time > 0) AND (Table2.dbo.E15.TSO <= 8)
ORDER BY Table1.date_removed DESC
What does the above query look like in PySpark code? Any help is greatly appreciated :)
This isn't really an answer to your question but is demonstrating how much cleaner your queries can look with some formatting. I also reworked the where predicates a little bit to avoid redundancy and fixed the logical problems with your parenthesis.
SELECT Table1.Part
, Table1.Serial
, Table1.AIRCRAFT_NUMBER
, Table1.date_removed
, Table2.dbo.E15.TIME
, Table2.dbo.E15.TSO
, data.dbo.EE18.Allowable_Time
, CASE WHEN (data.dbo.EE18.Allowable_Time > 0) THEN data.dbo.EE18.Allowable_Time - Table2.dbo.E15.TSO END AS CAL
FROM Table1 t1
INNER JOIN Table2.dbo.E15 ON Table1.SEQ_ID = Table2.dbo.E15.SEQ_ID
AND Table1.Part = Table2.dbo.E15.Part
AND Table1.Serial = Table2.dbo.E15.Serial
AND Table1.DATE_REMOVED_DESCENDING = Table2.dbo.E15.DATE_REMOVED_DESCENDING
INNER JOIN data.dbo.EE18 ON Table2.dbo.E15.Part = data.dbo.EE18.PART_NUMBER
AND Table2.dbo.E15.TIME = data.dbo.EE18.TIME
WHERE Table1.Part LIKE '18%'
AND data.dbo.EE18.Allowable_Time > 0
AND
(
Table2.dbo.E15.TIME = 'I'
AND
Table2.dbo.E15.TSO <= 2
)
OR
(
Table2.dbo.E15.TIME = 'T'
AND
Table2.dbo.E15.TSO <= 20
)
OR
(
Table2.dbo.E15.TIME = 'L'
AND
Table2.dbo.E15.TSO <= 8
)
ORDER BY Table1.date_removed DESC

SQL Query conversion from sybase to SQL Server

select a.dda_pk
from direct_table a
where a.dda_type = 'B'
and a.dda_status = 'D'
and a.dda_location = '01'
group by a.dda_emp_idno
having dda_pk < max(a.dda_pk)
and a.dda_status = 'D'
and a.dda_location = '01'
Column 'direct_deposit_audit.dda_pk' is invalid in the HAVING clause
because it is not contained in either an aggregate function or the
GROUP BY clause.
This is based on a assumption that the SQL returns rows for each dda_emp_idno
where dda_pk is smaller than the maximum dda_pk for that dda_emp_idno.
This should do the same thing in SQL Server:
select dda_pk
from (
select
dda_pk,
dense_rank() over (partition by dda_emp_idno order by dda_pk desc) as RN
from
direct_table a
where
a.dda_type = 'B'
and a.dda_status = 'D'
and a.dda_location = '01'
) X
where RN > 1
All the elements in group by must be in select clause so you can try this:
select a.dda_pk
from direct_table a
where a.dda_type = 'B'
and a.dda_status = 'D'
and a.dda_location = '01'
group by a.dda_pk
having a.dda_pk < max(a.dda_pk)
and a.dda_status = 'D'
and a.dda_location = '01'
Without having dug into this query, let me just note that Sybase ASE has much looser semantics around the GROUP BY than most other databases. This means that queries with GROUP BY that run iN ASE may raise an error in other databases.
For more info, see http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.help.ase.15.7/title.htm

T-Sql Query : how to make two conditions met in one record and not one only

I have a query the following query :
select Opp.[ID], Opp.ContactID, Opp.RTSID, Opp.[ProjectName],
CONVERT(varchar, Opp.[PurchaseDate], 103) as PurchaseDate,
CONVERT(varchar,Opp.[SubmissionDate],103) as SubmissionDate,
Opp.[Cost], Opp.[Selling], Opp.[CompanyName], Opp.[Telephone],
Opp.[Fax], Con.[ContactName], Con.[ContactPosition],
Con.[ContactDirectPhone], Con.[ContactMobile], Con.[ContactEmail],
lookup.DescriptionEn as ProjectStatus, Opp.[Wining], Opp.[Remark],
Opp.[CustomerReference], Sales.FName + ' ' + Sales.LName as SalesMan
from Opportunities Opp inner join Sales on Opp.Sales_Num = Sales.Sales_Num
left join
(select MINOR, DescriptionEn from lookup_table where MAJOR = '1') lookup
ON lookup.MINOR = Opp.ProjectStatus
left join
(select ID, ContactName, ContactPosition, ContactDirectPhone, ContactMobile,
ContactEmail from Contacts) Con ON Con.ID = Opp.ContactID
where (lookup.DescriptionEn = #ProjectStatus or #ProjectStatus ='-1') and
(Opp.Sales_Num = #SalesMan or #SalesMan ='-1') and
(Opp.Selling >= #Selling or #Selling ='0') and
(lookup.MINOR <> '7' and datediff(day , Opp.SubmissionDate , getdate()) < 30 )
End
The last Line which conntains Condition and (lookup.MINOR <> '7' or .......)
doesn't work as expected it either gets the records where MINOR <> '7' or other
I want to specify the two condition to met in one record only
How to do that?
Replace
(lookup.MINOR <> '7' and datediff(day , Opp.SubmissionDate , getdate()) < 30 )
by
(lookup.MINOR <> '7' OR datediff(day , Opp.SubmissionDate , getdate()) < 30 )
Use AND instead of OR.

Resources