I am writing a code in SQL for Access. The query asks three questions. I have three categories -- I'll just use the categories 'country', 'city', 'street' for now. I am trying to figure out how to make it so that you only have to enter one answer even though it asks you 3. But if you answer two, it will give you the like terms. For example, if I answered Georgia and Atlanta, Atlanta Georgia would show up. Or if I entered Canal in 'street' and Louisiana, every street named Canal in Louisiana would show up.
Currently, if I typed out Canal and Louisiana, the query would show me everything listed under Louisiana and every street titled Canal (even the ones not in Louisiana).
SELECT *
FROM File
WHERE (((File.State)=[Enter the state]))
OR (((File.City)=[Enter the city]))
OR (((File.Street)=[Enter the street]));
I think you should be able to do it by using AND rather than OR to connect the criteria for the different columns, but not using the criteria for a column if its parameter wasn't given.
SELECT *
FROM File
WHERE ( ([Enter the state] = '') OR (File.State=[Enter the state]) )
AND ( ([Enter the city] = '') OR (File.City=[Enter the city]) )
AND ( ([Enter the street] = '') OR (File.Street=[Enter the street]) );
I'm kind of rusty with Access, so I'm not sure if the parameter will be null or '' if nothing is entered, so it might need to be adjusted a little for that.
SELECT * FROM File WHERE
(((File.State)='[Enter the state]'))
OR (((File.City)='[Enter the city]'))
OR (((File.Street)='[Enter the street]'));
You just needed some quotes around them because they are strings.
Related
I'm trying to modify a report that shows health assessments using SQL. On the report, I would like to add a section for comments that were added to the health assessments. I was able to add the comment section, and with a suggestion provided here, I used SUBSTRING to limit the number of characters displayed on the report to 1000 as opposed to 8000.
The issue I'm experiencing now is with limiting the number of characters displayed for the option 'Other' as shown below. I used SUBSTRING (ex: SUBSTRING(HltNutrition.Comment, 1, 1000)) for all of the assessments and have included the Nutrition assessment as an example (which is working correctly) along with the snippet of code featuring the 'Other' (Chronic) option (which is not working correctly). I replaced 3 with 1 and although this did not produce an error, it did not have the intended effect for 'Other' as SUBSTRING([HealthAssessName].Comment, 1, 1000).
Any assistance is appreciated. Thank you in advance.
-- Nutrition
INSERT INTO #ChronicCondition(IdApplicant, ExamDate, Condition, TreatmentNeeded, TreatmentReceived, Status, Comment)
SELECT #Enroll.IdApplicant,
HltNutrition.ExamDate,
'Nutrition',
HltNutrition.TrtNeed,
HltNutrition.TrtStatus,
HltNutrition.Status,
SUBSTRING (HltNutrition.Comment, 1, 1000)
FROM #Enroll
JOIN HltNutrition ON HltNutrition.IdApplicant = #Enroll.IdApplicant
WHERE HltNutrition.Overweight = 1
-- Chronic
INSERT INTO #ChronicCondition(IdApplicant, ExamDate, Condition, TreatmentNeeded, TreatmentReceived, Status, Comment)
SELECT #Enroll.IdApplicant,
HltChronic.ExamDate,
CASE ChronicCondition.Id
WHEN 3 THEN 'Other' + ISNULL(' - ' + hltChronic.ConditionOther, '')
ELSE ChronicCondition.Condition
END,
HltChronic.TrtNeed,
HltChronic.TrtStatus,
hltChronic.Status,
SUBSTRING (HltChronic.Comment, 1, 1000)
FROM #Enroll
JOIN hltChronic ON hltChronic.idApplicant = #Enroll.idApplicant
JOIN ChronicCondition ON ChronicCondition.Id = hltChronic.Condition
Thank you for the assistance, I walked through the concern with the senior developer and found that the SUBSTRING function was not the cause of the issue. The problem I was encountering was due to data entry that was used for testing the report. The code I added is actually correct and the problem has been resolved.
Thanks again for any assistance that was provided.
My company uses numbers as a system identifier to branches. The problem is my end users do not like seeing 000201 as a branch name. Therefore I am trying to convert these numbers to a string and then roll up the satellite locations into the main branch. The branch format is as follows:
BBBBSS so, as an example, the Nashville main branch will follow 000201 and all satellites would follow sequentially 000202, 000203, 000204.
I want all of our details to roll up into "Nashville". So any instance that ORGID is like 0002** it would roll up everything into a field named "Nashville".
Sorry if I'm not too clear. I've been banging my head against the wall so my thoughts are jumbled.
If I understand your question, there are at least Two ways i can think of accomplishing this ;
The 1st way is straight forward, you'd add a case statement for each Branch, if you have many branches i'd go with the 2nd way.
Select case SUBSTRING(cast(Branch.Id as varchar(10)), 1, 4 )
when '0002' then 'Nashville'
when '0003' then 'Branch 03'
when '0004' then 'Branch 04'
else SUBSTRING(cast(Branch.Id as varchar(10)), 1, 4 ) end OrgName,
COUNT(*)
from Branch group by SUBSTRING(cast(Branch.Id as varchar(10)), 1, 4 )
This 2nd way you would have a separate table to Hold Branch Name, etc. For demonstration i will call this table OrgTable with a OrgId containing your "0002" Ids, and a OrgName containing the "Nashville".
Select OrgTable.OrgName, count(*)
from Branch
inner join OrgTable on ( OrgTable.OrgId = SUBSTRING(cast(Branch.Id as varchar(10)), 1, 4 ))
Group By OrgTable.OrgName
I haven't checked that the SQL above is without syntax errors, but hopefully you get the picture.
HTH,
You can create a simple formula in CR to convert your ORGID to the branch name:
//Convert ORGID to string and save branch code
local stringvar branch := left(totext({Table.ORGID},0,''),4);
//Display city based on branch code
select branch
case "0002" : "Nashville"
case "0003" : "Other City"
<...>
default : "No matching branch!"
Im having trouble joining two varchar(31) fields on sql server 2008. below is my query and it works fine
select A.CustId,A.Country,B.Country from [ACC].[dbo].[Customer] as A
left join
[Task Centre].[dbo].[CountryCodes] as B on A.Country=B.Country]
the results are as follows
CustomerA United Kingdom Null
CustomerB Ireland Ireland
CustomerC Spain Spain
CustomerD South Africa Null
South Africa and United Kingdom don't match even though they are in both dbs
I have tried to replace the space but its very slow and doesnt work. I think its something to do with the whitespace but I cant find the right command to achieve what I want.
Bear with me if I have omitted anything as Im a novice, I have also searched everywhere for an answer but cant find one that works for me.
Any help is greatly appreciated
Mike
Try to execute the following query on both tables. This will tell you if there's any "hidden" difference between the tables (for example, blank characters, line breaks, etc.):
select Country, CAST(Country AS VARBINARY) AS BinaryCountry
from [ACC].[dbo].[Customer]
where Country = 'United Kingdom'
select Country, CAST(Country AS VARBINARY) AS BinaryCountry
from [Task Centre].[dbo].[CountryCodes]
where Country = 'United Kingdom'
The column BinaryCountry should show a different value, if the content of the Country-columns are not exactly the same. If that is the case, consider correcting the error in either table. Once you've made sure that the value is the same in both tables, your join should work just fine.
Edit: The problem turns out to be a non-breaking space character in the Task Centre-table. To workaround this, use the following in your join criteria:
ON A.Country = Replace(B.Country, CHAR(0xA0), ' ')
Try this:
If any space is in value you need to trim and check
SELECT A.CustId, A.Country, B.Country
FROM [ACC].[dbo].[Customer] AS A LEFT JOIN
[Task Centre].[dbo].[CountryCodes] AS B
ON LTRIM(RTRIM(A.Country)) = LTRIM(RTRIM(B.Country))
If the difference is whitespace, then I guess this might work for you. It will be slow though, since it won't be able to use any indexes:
select A.CustId,
A.Country,
B.Country
from
(
SELECT A.CustId,
A.Country,
LOWER(REPLACE(A.Country, ' ', '')) AS CleanedCountry
FROM [ACC].[dbo].[Customer] as A
) A
left
join
(
SELECT B.Country,
LOWER(REPLACE(B.Country, ' ', '')) AS CleanedCountry
FROM [Task Centre].[dbo].[CountryCodes] as B
) B
on A.CleanedCountry=B.CleanedCountry
You would only need the lower if your collation is case sensitive...
I'm fairly new to SQL, I'm actually just building a small database in Access right now although if there is necessary functionality that Access can't do I'll remake the tables in SQL Server.
Here's my situation, I have a list of names that come from a data dump from a third party. In our database I need to be able to compare first and last names in separate columns.
I've been trying to use InStr, Left and Right - but am getting hung up with weird results
Left([NewClaims]![Claimant Full Name],InStr([NewClaims]![Claimant Full Name],",")-1) AS LastName,
Right([NewClaims]![Claimant Full Name],InStr([NewClaims]![Claimant Full Name], ", ")+2) AS FirstName,
On some names it works perfectly
West, Krystal --becomes--> LastName = West, FirstName= Krystal
On other names, similar in formant it doesn't work
Dalton, Kathy ----> LastName = Dalton, First Name = ON, KATHY
On Names with middle initials I get
Earles, Barbara A. ----> LastName = Earles, FirstName= ARBARA A. (one missing letter)
OR
Beard, Chekitha G. ----> LastName = Beard, FirstName= KITHA G. (three missing letters)
I'm frustrated. Can anyone offer another idea on how to make this work? I seem to have the last name down, but I can't get the first name to be consistently correct.
Try this. But I'm assuming that there's always a comma that separates last name from first name.
select
txt,
LastName = left(txt,charindex(',',txt)-1),
FirstName = ltrim(right(txt,len(txt)-charindex(',',txt)))
from (
select 'West, Krystal' as txt union all
select 'Dalton, Kathy' union all
select 'Earles, Barbara A.' union all
select 'Beard, Chekitha G.'
) x
Your mistake was that when using right to extract first name, you didn't take the length of the string under consideration.
I have two tables, one of which contains 3000 area codes (so just the first half of the postcode) and the other table containing shops details with a column called postcodes_covered which are all the area codes that a particular shop covers for example:
shop 1 (AB1,AB2,AB3,AB4,AB5...), shop 2 (E15,E13,E14 ...) etc. I need to create a report which contains the 3000 area codes and a column that says "Yes" if an area code from table 2 is contained in table 1 or "No" if that area code is not covered. I have written an SQL query which works fine however, i need to write it in codeigniter. The code i have written for codeigniter doesn't seem to work and i don't know why?
SQL query:
select bodyshops_postcode_allocation.area_code,if(postcodes_covered is null,"No","Yes") as "YeN" from bodyshops_postcode_allocation left join bodyshops on bodyshops.postcodes_covered like concat("%",bodyshops_postcode_allocation.area_code,"%");
Codeigniter:
function postcode_allocation()
{
$this->db->select('bodyshops_postcode_allocation.area_code as area_code')
->select('IF(bodyshops.postcodes_covered is null, "No", "Yes") as match_found')
->join('bodyshops', 'bodyshops.postcodes_covered LIKE CONCAT("%",bodyshops_postcode_allocation.area_code,"%")')
->from('bodyshops_postcode_allocation');
$this->load->dbutil();
$data = $this->dbutil->csv_from_result($this->db->get(''));
$this->output->set_header("Content-type: application/vnd.ms-excel");
$this->output->set_header("Content-disposition: attachment; filename=postcode_allocation.csv; size=".strlen($data));
$this->output->set_output($data);
}
When using SQL function like this in CodeIgniter, you need to tell it not to try to escape the query.
->select('IF(bodyshops.postcodes_covered is null, "No", "Yes") as match_found', FALSE)
The FALSE tells CodeIgniter to leave the string as-as and not try to add backticks to it. It doesn't know how to add them in this case, so it messes up your query.
P.S. your join needs to be:
->join('bodyshops', 'bodyshops.postcodes_covered LIKE CONCAT("%",bodyshops_postcode_allocation.area_code,"%")', 'left')
If you want a LEFT JOIN, you need to tell it so.
P.P.S. $this->db->get('') should really just be $this->db->get(). Don't pass it a blank string.