SQL - extract multiple values - sql

I have an SQL table with Member ID's.
Each member has information regarding their insurance claims listed in the table.
One column lists insurance ID's in relation to Member-ID.
for example:-
|Member ID | Insurance Code |
----------------------------------
|C#$###!1231 | 67 |
Now the issue is the same member could have different Insurance Code#'s as a part of previous claims.
For example between 2010 -2011, the member had a claim Code = 67
But for 2011 - 2012, the member had a claim Code = 3
Now when I create a SQL query, I only get one value for claim code.... how can I get all the values, say 67, 3, and 110? Such that I can respond to all claims that the member has been a part of.
// SQL QUERY to gather member information.
DMS.ADOQuery1.SQL.Clear;
DMS.ADOQuery1.SQL.Add('select HPFROMDT, HPthruDt, MEMBERKEY, MEMBHPKEY, OPFROMDT, OPTHRUDT, HPCODEKEY' +
' from MEMBHP' +
' where MEMBERKEY = ''' + MembKey + ''' and OPTHRUDT >= ''' + init_date + ''' and OPFROMDT <= ''' + final_date +''' and OPFROMDT < OPTHRUDT'
);
// Showmessage(DMS.ADOQuery1.SQL[0]);
DMS.ADOQuery1.Open;
// Adding the query values to the appropriate variables.
HPCodeKey := (DMS.ADOQuery1.FieldByNAme('HPCODEKEY').AsString);
DMS.ADOQuery1.Close;

Check all the records returned by query, not only the first one.
Check also filter dates in SQL statement (where condition).
// SQL QUERY to gather member information.
DMS.ADOQuery1.SQL.Clear;
DMS.ADOQuery1.SQL.Add('select HPFROMDT, HPthruDt, MEMBERKEY, MEMBHPKEY, OPFROMDT, OPTHRUDT, HPCODEKEY' +
' from MEMBHP' +
' where MEMBERKEY = ''' + MembKey + ''' and OPTHRUDT >= ''' + init_date + ''' and OPFROMDT <= ''' + final_date +''' and OPFROMDT < OPTHRUDT'
);
// Showmessage(DMS.ADOQuery1.SQL[0]);
DMS.ADOQuery1.Open;
while not DMS.ADOQuery1.Eof do
begin
// Adding the query values to the appropriate variables.
Showmessage(DMS.ADOQuery1.FieldByNAme('HPCODEKEY').AsString);
DMS.ADOQuery1.Next;
end;
DMS.ADOQuery1.Close;

Related

How can I check the maximum value from a set of tables in SQL Server (if possible)?

We have a set of databases (80 in total). Every single one has a table called tblProfessions. The tables are not standardized. For example:
EDIT: all the databases are on the same server.
The DB1.dbo.tblProfessions is like:
intProfessionCode
strProfessionDescription
1
lawyer
2
dentist
...
...
30
doctor
And the DB72.dbo.tblProfessions is as follows:
intProfessionCode
strProfessionDescription
1
designer
2
butcher
...
...
80
chef
Suppose I ran a script from DBO1 to DBO72, and I found that the biggest table has 80 entries (in this case the DBO72 is the biggest one).
By my limited knowledge, all I know is to run the below script database by database, and write it down in a spreadsheet manually:
SELECT MAX(intProfessionCode) FROM [DB].dbo.tblProfessions;
Is there a script to run and loop through all the tblProfessions and get the one with the most entries? All I want is the biggest number found.
Thanks in advance.
You should be able to do something like this:
WITH dat
AS
(
SELECT 'db1' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB1.dbo.tblProfessions
UNION ALL
...
UNION ALL
SELECT 'db72' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB72.dbo.tblProfessions
)
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
FROM dat) y
ON dat.max_intProfessionCode = y.max_intProfessionCode_overall
For situations like this, I usually query the catalog to write the above script rather than typing it out:
WITH
dat AS
(
SELECT STRING_AGG('SELECT ''' + QUOTENAME(s.name) + ''' AS db,
MAX(intProfessionCode) AS max_intProfessionCode
FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME('dbo') + '.' + QUOTENAME('tblProfessions') + '
UNION ALL',' ') AS s
FROM sys.databases s
WHERE s.name LIKE 'DB%' --EDIT APPROPRIATELY
)
SELECT 'WITH dat
AS
(' + SUBSTRING(s,1,LEN(s) - LEN(' UNION ALL')) + ')
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
FROM dat) y
ON dat.max_intProfessionCode = y.max_intProfessionCode_overall' AS scrpt
FROM dat;
Make sure the above is only returning data for the appropriate databases by editing the WHERE clause in the CTE, then copy the output, paste elsewhere and run it to get your results.

Big Query: how to use Variable and loops with column names

I am trying to use a loop to update a table in Bigquery. My table structure is as following (with 100 columns and thousands of rows):
DATE
PERIOD1
PERIOD2
PERIOD3
PERIOD4
PERIOD5
PERIOD6
PERIOD...
PERIOD100
2021-01-01
row
2021-02-01
row
For each date, I would need to use a loop to populate the values with something like
---
DECLARE VAR_PERIOD INT64 DEFAULT 1
LOOP
IF PERIOD > 100 THEN LEAVE;
END IF;
---
update `mydataset.mytable` set CONCAT('PERIOD',VAR_PERIOD) = (select{+my query})
which obviously cannot work, so I'm wondering what alternative method can be used to easily update my table columns ?
For this you can try using BigQuery API client libraries link.
There are more languages available but I am using python here.
You can directly start in cloud shell. There you can write a Python program to
do your job.
There is some assumption I am taking regarding your requirements :
You want to use SELECT clause to get some value and using which you want to
update values of Period columns.
from google.cloud import bigquery
''' Construct a BigQuery client object. '''
client = bigquery.Client()
query = """
select col_name from `projectID.dataset.table`
where condition
"""
''' Make an API request. '''
query_job = client.query(query)
''' Store the value of query result in some variable (value). '''
for row in query_job:
value = row[0]
'''
Creating the query to update the columns using the value.
UPADTE `projectID.dataset.table`
SET Period1 = Period1 + value, Period2 = Period2 + value ...
where condition
'''
query = "UPDATE `projectID.dataset.table` SET "
for i in range(1,101):
query += 'period'+str(i)+' = ' + 'period'+ str(i) + ' + ' +str(value) +','
query = query[0:-1]
query += ' WHERE condition'
''' Make an API request. '''
query_job = client.query(query)
All BigQuery Update statement must have a WHERE Clause. If you
want to update all the rows than in WHERE condition mention TRUE link.

Hi,. I want ssms query (SQL query)

I want ssms query (SQL query) which will help me in getting YTD data.
Example if I am in Jan month then take Jan data and create column to add month=1,
if I am in feb month then take Jan + feb and month column=2.
Which means when I will in feb I will get Jan with month=1 and Jan+ feb with month=2. And so on...
SELECT will be able to add months together for you, here's a query I ran on my crime database recently, you can change as needed:
--returns the total of all 2019
select LGA, ([Jan-2019] + [Feb-2019] + [Mar-2019] + [Apr-2019] + [May-2019] + [Jun-2019] + [Jul-2019] + [Aug-2019] + [Sep-2019] + [Oct-2019] + [Nov-2019] + [Dec-2019])
FROM Crime_LGA
alternatively, you can make a new column for each MTD, or maybe even a new table. Here's some code i used recently to add columns:
--to add a total 2019 column
ALTER TABLE Crime_Suburb
ADD Total_2010 int NOT NULL DEFAULT (0),
--to add values to the column
UPDATE Crime_Suburb
SET Total_2010 = ([Jan-2010] + [Feb-2010] + [Mar-2010] + [Apr-2010] + [May-2010] + [Jun-2010] + [Jul-2010] + [Aug-2010] + [Sep-2010] + [Oct-2010] + [Nov-2010] + [Dec-2010])
FROM Crime_Suburb

dynamic sql query formation using pyhon

I am new to the python and want to form SQL query dynamically in python.so tried below sample code:
empId = 12
query = ''' select name, ''' +
if empId > 10:
'''basic_salary'''
else:
''' bonus'''
+ ''' from employee '''
print(query)
but , getting syntax error. does anyone knows how to form dynamic query in python.
You need to indicate that the assignment to query continues on the next line, which you can do with a \ at the end of the line. Also, you need to write the if statement as an inline if expression as you can't have an if statement in the middle of an assignment statement:
empId = 12
query = ''' select name, ''' + \
('''basic_salary''' if empId > 10 else ''' bonus''') + \
''' from employee '''
print(query)
Output:
select name, basic_salary from employee
If you have multiple conditions, you can just add to query in the conditions. For example:
empId = 6
query = 'select name, '
if empId > 10:
query += 'basic_salary'
elif empId > 5:
query += 'benefits'
else:
query += 'bonus'
query += ' from employee'
print(query)
Output
select name, benefits from employee
#dynamic sql query formation using python
#This is for PostgresSQL you can use this for other queries as well:
def updateQuery(self,tableName,setFields,setValues,whereFields,whereValues):
print("Generating update query started")
querySetfields = None
queryWhereFields = None
# Loop for set fields
for i in range(len(setFields)):
if querySetfields is None:
querySetfields=setFields[i]+"='"+setValues[i]+"'"
else:
querySetfields=querySetfields+","+setFields[i]+"='"+setValues[i]+"'"
# Loop for whereFields
for i in range(len(whereFields)):
if queryWhereFields is None:
queryWhereFields=whereFields[i]+"='"+whereValues[i]+"'"
else:
queryWhereFields=queryWhereFields+","+whereFields[i]+"='"+whereValues[i]+"'"
#Form the complete update query
query="UPDATE "+tableName+" SET "+querySetfields+" WHERE "+queryWhereFields
print("Generating update query completed")
return query
print(updateQuery(None,"EMPLOYEE_DETAILS",["EMPI_ID","EMP_LANID","EMP_NAME","EMP_EMAIL"],["A","B","C"],["EMPI_ID","EMP_LANID"],["X","Y","Z"]))

Why doesn't this GROUP BY query work?

I'm querying my Access table with this query:
SELECT (VIN&' '&Make&' '&Model&' '&CarYear&' '&ExColor&' '&InColor&' ')as CarDescript
FROM TestTable
WHERE (WorkOrderNumber='$workorder')
GROUP BY AssignedEmp;
But a similar type of query works just fine in this SQL Fiddle
Even if I replace the long (VIN&' '&....) with VIN it still doesn't work.
EDIT: Schema of the table is
WorkOrderNumber - Priority - JobStage - WorkItem - AssignedEmp - DueDate - VIN - Make - ... - InColor
In general use + instead of & for SQL. (Access will allow this however).
In a group by you need to pick which one in the group to use (if you are using mysql like your example it just picks a random one, see this fiddle) so to fix this in the general case for your example:
SELECT (max(VIN) + ' ' + max(Make) + ' ' + max(Model) + ' ' + max(CarYear) + ' ' + max(ExColor) + ' ' + max(InColor) + ' ')
as CarDescript
FROM TestTable
WHERE WorkOrderNumber='$workorder'
GROUP BY AssignedEmp;