Merge two sql queries into one - sql

I've been working on a system service for a client for a while and need some help, I need to merge two sql queries into one. The first part of the query is to look at the master sequence number and count it, after which the query must update a field. I have the two queries below if anyone can help with this problem.
Count query
SELECT master_seq, count(master_seq) as NofH
FROM [ZS_CS_EVO_Integration].[dbo].[CS_Consolidation]
where delivery_date = '2016-07-01'
GROUP BY master_seq
order by master_seq
Update Query
(" UPDATE [dbo].[CS_Consolidation]"
+ " SET [split_dlv] = 1"
+ " FROM [dbo].[CS_Consolidation]"
+ " WHERE"
+ " [master_seq] <> 0 AND CONVERT(DATE,delivery_date) = '" + yesterday + "'", IntConnect);

You can put the first part into CTE, then join and UPDATE:
DECLARE #delivery_date DATE = '2016-07-01'
;WITH cte AS (
SELECT master_seq
FROM [ZS_CS_EVO_Integration].[dbo].[CS_Consolidation]
where delivery_date = #delivery_date and [master_seq] <> 0
GROUP BY master_seq
HAVING count(master_seq) > 1
)
UPDATE c
SET [split_dlv] = 1
FROM [dbo].[CS_Consolidation] c
INNER JOIN cte t
ON t.master_seq = c.master_seq and c.delivery_date = #delivery_date

Related

Trying to combine 2 columns in sql query

SELECT SubscriberKey, COUNT(*) AS TotalSentLast180Days
FROM (
SELECT s.SubscriberKey
FROM ENT._Sent s
INNER JOIN ENT.AllSubscribershistroyland ROCS
ON ROCS.SubscriberKey = s.SubscriberKey
WHERE ROCS.SLSegment__c = 'S4 - real-love'
AND 'S6 - real-love'
AND s.OYBAccountID = '85208879'
AND s.EventDate >= DATEADD(DAY, -180, GETDATE())
) t
GROUP BY SubscriberKey
So in the " AllSubscribershistroyland " their are 2 columns that are called 'S4 - Dutch real-love' and 'S6 - real-love'. Im trying to run the query to see how many subscribers are in those 2 columns. I cant seem to combine them but when i run the query for example with one column i do get a result back. I tried the ' AND ' to combine the 2 columns but i get an error code of "
Error saving the Query field. An expression of non-boolean type specified in a context where a condition is expected, near 'AND'.** "
if anyone can help me i would be very grateful
I am not entirely sure what you're trying to do, but if you are just trying to include both of your titles in the where clause for the same column then you could use the IN Clause:
SELECT SubscriberKey, COUNT(*) AS TotalSentLast180Days
FROM (
SELECT s.SubscriberKey
FROM ENT._Sent s
INNER JOIN ENT.AllSubscribershistroyland ROCS
ON ROCS.SubscriberKey = s.SubscriberKey
WHERE ROCS.SLSegment__c in ('S4 - real-love', 'S6 - real-love')
AND s.OYBAccountID = '85208879'
AND s.EventDate >= DATEADD(DAY, -180, GETDATE())
) t
GROUP BY SubscriberKey

Tuning the update statement in SQL Server or upgrade the query in T-SQL like Oracle plsql (for idx update)

Here is my update query in SQL Server, it is taking a long time to execute. I need help to re-write the query.
UPDATE d
SET d.CA_PAID_TO_DATE = s.canextpdate
FROM
(SELECT LTRIM(RTRIM(POLNUM)) POLNUM, CA_PAID_TO_DATE
FROM [DataAnalytics].[dbo].[tbla_hst_policy_history]
WHERE transmonth = '202112'
AND CA_PAID_TO_DATE IS NULL) AS d
INNER JOIN
(SELECT
LTRIM(RTRIM(CAPOLNUM)) CAPOLNUM,
CASE
WHEN LEFT(canextpdate, 2) > 85
THEN '19' + canextpdate
ELSE '20' + canextpdate
END canextpdate
FROM [DataAnalytics].[dbo].[tblh_lldca]
WHERE transmonth = '202112' ) AS s ON (d.POLNUM = s.CAPOLNUM);
Your rtrim() and ltrim() is completely questionable. You would be killing the use of indexes that way.
That one put aside, your statement is unnecessarily complex than what it needs to be. You could write it simpler and should be faster even in the existence of those ltrim(rtrim)()):
UPDATE d
SET CA_PAID_TO_DATE = CASE
WHEN LEFT(canextpdate, 2) > 85
THEN '19' + canextpdate
ELSE '20' + canextpdate
END
FROM
SELECT canextpdate
FROM [DataAnalytics].[dbo].[tblh_lldca] d
WHERE transmonth = '202112' and
exists (
SELECT * FROM [DataAnalytics].[dbo].[tbla_hst_policy_history] h
WHERE h.transmonth = '202112'
AND h.CA_PAID_TO_DATE IS NULL
AND LTRIM(RTRIM(h.CAPOLNUM)) = LTRIM(RTRIM(d.POLNUM))
);
Instead of ltrim(rtrim()), use a varchar\nvarchar field and fill with trimmed values once (and create index on that field).

SQL - Join Queries

Here I have two tables as student_information and exmaination_marks.
examination_marks table have 3 columns for three subjects and include their marks.
I want to select the roll_number and name of the student from the student_information table where sum of the three subject's marks in examination_marks table is less than 100.
Both table has roll_number as primary key.
Here is the query I wrote.
select
si.roll_number,
si.name
from
student_information as si
left outer join examination_marks as em on
si.roll_number = em.roll_number
where
sum(em.subject_one + em.subject_two + em.subject_three) < 100;
But I got an error saying "ERROR 1111 (HY000) at line 1: Invalid use of group function"
Can any one help me with this?
sum(em.subject_one + em.subject_two + em.subject_three)< 100
this is the problem . Try these
Where (SELECT subject_one + subject_two + subject_three FROM examination_marks WHERE em.roll_number = si.roll_number) < 100
SUM is an "aggregate function" which can only be used inside a query which has a GROUP BY clause.
To get the sum of values within the same row you need to use the + operator. If the columns are NULL-able then you'll also need to use COALESCE (or ISNULL) to prevent NULL values invalidating your entire expression.
Like so:
SELECT
si.roll_number,
si.name,
COALESCE( em.subject_one, 0 ) + COALESCE( em.subject_two, 0 ) + COALESCE( em.subject_three, 0 ) AS sum_marks
FROM
student_information AS si
LEFT OUTER JOIN examination_marks AS em ON
si.roll_number = em.roll_number
WHERE
COALESCE( em.subject_one, 0 ) + COALESCE( em.subject_two, 0 ) + COALESCE( em.subject_three, 0 ) < 100;
(If you're wondering why the COALESCE( em.subje... expression is repeated in the SELECT and WHERE clauses, that's because SQL is horribly designed by (obscene profanities) is an unnecessarily verbose language).

How to select last set of rows from query in ms access

I am trying to run two queries one that selects the first 22 rows and one that selects the remaining rows of the query. I am able to select the top 22 rows. But now I need to select the next 22 rows. Basically I have 2 reports in access, one that displays the first 22 rows, and the next would display the next 22 rows.Any help would be greatly appreciated. Does anyone know a function that could send me in the right direction?
Here is my query so far that select the top 22 rows:
SELECT TOP 22[UB-04_line_items].client_id, [UB-04_line_items].revenue_code, Revenue_Codes.rev_code_desc, [UB-04_line_items].total_chgs, [UB-04_line_items].cpt_code, [UB-04_line_items].service_units, [UB-04_line_items].service_date, [UB-04_line_items].total_chgs, Sum(IIf(IsNull([reason_code])=False,[disputed_amount],0)) AS [AMT DISPUTED], GetList("Select Distinct reason_code From [Itemized_statements] As T1 Where t1.reason_code <> NULL AND t1.client_id = " & [Itemized_statements].client_id & " AND T1.revenue_code = " & [Itemized_statements].revenue_code & "","",", ") AS [Err Code]
FROM [UB-04_line_items] INNER JOIN (Itemized_Statements LEFT JOIN Revenue_Codes ON Itemized_Statements.revenue_code = Revenue_Codes.revenue_code) ON [UB-04_line_items].client_id = Itemized_Statements.client_id
GROUP BY [UB-04_line_items].client_id, [UB-04_line_items].revenue_code, Revenue_Codes.rev_code_desc, [UB-04_line_items].cpt_code, [UB-04_line_items].service_units, [UB-04_line_items].service_date, [UB-04_line_items].total_chgs, [UB-04_line_items].total_chgs, Itemized_Statements.client_id, Itemized_Statements.revenue_code
HAVING ((([UB-04_line_items].client_id)=[Itemized_Statements].[client_id]) AND ((Itemized_Statements.client_id)=[forms]![frmClients]![client_ID]) AND ((Itemized_Statements.revenue_code)=[UB-04_line_items].[revenue_code]))
ORDER BY Itemized_Statements.client_id;
Consider using a calculated row number by running count of client_id and revenue_code (assuming this pair is unique in the aggregate query). Then, use this subquery in WHERE clause to condition the needed range. Be sure to remove the TOP clause from stored query.
Top 22 (substitute Qry for actual stored query name)
SELECT (SELECT Count(*)
FROM Qry sub
WHERE sub.client_id < Qry.client_id
OR (sub.client_id = Qry.client_id
AND sub.revenue_code <= Qry.revenuce_code)) As RowNo, *
FROM Qry
WHERE (SELECT Count(*)
FROM Qry sub
WHERE sub.client_id < Qry.client_id
OR (sub.client_id = Qry.client_id
AND sub.revenue_code <= Qry.revenuce_code)) <= 22
Next 22 (substitute Qry for actual query name)
SELECT (SELECT Count(*)
FROM Qry sub
WHERE sub.client_id < Qry.client_id
OR (sub.client_id = Qry.client_id
AND sub.revenue_code <= Qry.revenuce_code)) As RowNo, *
FROM Qry
WHERE (SELECT Count(*)
FROM Qry sub
WHERE sub.client_id < Qry.client_id
OR (sub.client_id = Qry.client_id
AND sub.revenue_code <= Qry.revenuce_code)) BETWEEN 23 AND 44

Select 1 from dual where exists (select ....). Returns 1 even if the table is completely empty?

I'm using a Select 1 from dual statement to see if new data that comes into my system is actually new or not, if it is new then it's gonna be inserted, if it is not then it's gonna be updated in the database.
sql.CommandText = "select 1 from dual where exists (select * from my table where hour = " + hour + " and zone = '" + zone+ "' and date = TO_DATE('" + mydate + "','DD-MM-YY'))"
The problem however is that after running the statement, it returns the 1 value even if the conditions for it aren't met, even if the table is completely empty. How could this happen?
I'm using VB, .NET framework 3.5 and Oracle 10g.
I would suggest something like
SELECT COUNT(*) AS cnt
FROM mytable m
WHERE m.hour = hour
AND m.zone = zone
AND m.date = TO_DATE( mydate,'DD-MM-YY'))
AND ROWNUM = 1
The result will be either 0 or 1. Since you only care about the existence of the row, the ROWNUM = 1 will cause the query to quit as soon as it finds a matching entry and will prevent you from scanning the whole table.
You can use sign(count(1)) to get the count.
select sign(count(1)) cnt
from my_table
where hour = " + hour + " and zone = '" + zone+ "'
and date = TO_DATE('" + mydate + "','DD-MM-YY'))"