I am tallying student evaluation of instructors. I want my results to appear as:
Instructor1 - 145
Instructor2 - 23
Instructor3 - 394
The #CountInstructor# is not changing. It is only the first count is correct.
Using Coldfusion 8.
Thanks for your help.
<CFQUERY NAME="GetAll" datasource="eval" dbtype="ODBC">
SELECT ID, Instructor, Q1, Q2, Q3, Q4, Q5, Q6
FROM data
</CFQUERY>
<CFQUERY NAME="GetInstructor" datasource="eval" dbtype="ODBC">
SELECT DISTINCT Instructor
FROM data
ORDER BY Instructor
</CFQUERY>
<cfset myInstructor = ValueList(GetInstructor.Instructor)>
<cfset myCountInstructor = ValueList(GetAll.Instructor)>
<cfset CountInstructor = ListValueCount(myCountInstructor, myInstructor)>
<cfoutput query="GetAll">
<cfset CountInstructor = ListValueCount(myCountInstructor, GetInstructor.Instructor)>
#GetInstructor.Instructor# - #CountInstructor# <br />
</cfoutput>
Your use of ListValueCount(), within your query output loop, isn't helping you any. What is it you're trying to do exactly? If all you're looking to do is output a count as you go...
<cfoutput query="GetInstructor">
#GetInstructor.Instructor# - #GetInstructor.CurrentRow#
</cfoutput>
Otherwise, I'm just not sure what you want to do (and you need to scope all of the variables, including the query names).
<cfoutput query="GetInstructor">
<cfset CountInstructor = ListValueCount(myCountInstructor, GetInstructor.Instructor)>
#GetInstructor.Instructor# - #CountInstructor# <br />
</cfoutput>
Related
I need to create a list of country names within quotes and a comma at the end - except the last country name, like this:
(I'm using ColdFusion 10)
"Tuvalu",
"Uganda",
"Ukraine",
"United Arab Emirates",
"United Kingdom",
"Uruguay"
<cfquery name="query_names" datasource="MyDB">
select short_desc
from tbl_country
where NVL(short_desc,' ') <> ' '
order by short_desc
</cfquery>
<cfset TotalRec = "#query_names.Recordcount#">
<cfloop query="query_names">
<cfif query_names.Recordcount GT 271>
<cfoutput>
"#Trim(short_desc)#" & ","
</cfoutput>
<cfelse>
<cfoutput>
"#Trim(short_desc)#"
</cfoutput>
</cfif>
</cfloop>
This loop result in country names within quotes, but no comma. So my loop result in:
"Tuvalu"
"Uganda"
"Ukraine"
"United Arab Emirates"
"United Kingdom"
"Uruguay"
If you really need double quotes, it is probably simpler to append the quoted values to an array and convert it to a list at the end. The ArrayToList function automatically handles the commas for you:
<cfset names = []>
<cfloop query="query_names">
<cfset arrayAppend(names, '"'& short_desc & '"')>
</cfloop>
<cfoutput>#arrayToList(names)#</cfoutput>
Result:
"Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay"
Side note, if single quotes, i.e., ' are acceptable, it is even simpler. Skip the looping and just use QuotedValueList():
<cfoutput>#quotedValueList(query_names.short_desc)#</cfoutput>
Result:
'Tuvalu','Uganda','Ukraine','United Arab Emirates','United Kingdom','Uruguay'
I hope listQualify() does the same in pretty easier way. isn't it???
<cfset myQry = queryNew("country","varchar",[["Tuvalu"],["Uganda"],["Ukraine"],["United Arab Emirates"],["United Kingdom"],["Uruguay"]])>
<cfdump var="#listQualify(valueList(myQry.country),'"')#" />
Also we can use quotedValueList() as Leigh mentioned, if we need single quoted list.
User1557856, you were so close. Your answer is actually good, but for one point. If you correct it, you will get what you want.
The reason why you obtained a list without commas is this:
<cfif query_names.Recordcount GT 271>
This condition is always false apparently. So only the <cfelse></cfif> part of the code is run. That is the part without commas, hence the result.
If you modify your code slightly, as follows, you will get the desired result:
<cfloop query="query_names">
<cfif query_names.currentRow LT query_names.Recordcount>
<cfoutput>
"#Trim(short_desc)#",
</cfoutput>
<cfelse>
<cfoutput>
"#Trim(short_desc)#"
</cfoutput>
</cfif>
</cfloop>
I am just confusing myself with this one. I have a data log that is saved on the database as something like this:
Log-Date: 10/26/2012. Record created. Admission Date: 08/01/2012
Log-Date: 06/20/2013 Discharged. Discharge Date:10/15/2012
Reason for Discharge:01 - (routine discharge).
<!--- all other tracking info --->
I am trying to pull from this log only the discharges and sort/filter them by date. This log is saved in the database as one column varchar(MAX). I need to sort this data and only pull the discharge dates / reason using regex and then apply a filter. The end product should end up with me putting that array in a table with PATIENT | DISCHARGE DATE | DISCHARGE REASON My code right now is giving me some errors as it is leaving me with some empty array values. My question is that I need to remove those blank values and sort by the date, but I am unsure where to begin.
<cfquery name="getDischarge" datasource="#this.dsn#">
select PatientsName, LogData from Patient
</cfquery>
<cfoutput query="getDischarge" group="PatientsName">
<cfif LogData neq "">
<cfsavecontent variable="str">
#LogData#
</cfsavecontent>
<cfset possibilities = reMatch("Discharge Date?:(\d\d?/\d\d?/\d{4})\s*Reason for Discharge:\d* - ((?:(?!Log-Date:).)*)", str)>
<cfset dateArray = ArrayNew(2)>
<cfloop index="w"
array="#possibilities#">
<cfif w NEQ "">
<!--- create 1 dimensional temp array to hold DATE | REASON --->
<cfset tempArray = ArrayNew(1)>
<!--- trim our regex to have only the date & then DateFormat --->
<cfset theDate = #Mid(w, 16, 11)#>
<cfset formatDate = #dateformat('#thedate#','mm-dd-yyyy')#>
<!--- use our regex to find the reason for discharge --->
<cfset theReason = reMatch("Reason for Discharge:\d* - ((?:(?!Log-Date:).)*)", str)>
<!--- append our DATE | REASON to 1d temp array --->
<cfset ArrayAppend(tempArray, '#formatDate#')>
<cfset ArrayAppend(tempArray, '#theReason#')>
<!--- append our 1d array to our 2d array to output matching DATE | REASON --->
<cfset #ArrayAppend(dateArray, '#tempArray#')#>
</cfif>
</cfloop>
<cfdump var="#dateArray#">
</cfif> <!--- logdata neq "" --->
</cfoutput>
To me, logically, this should work and omit blank values, but this is what I get when I dump this data:
Looks like you are struggling with the Jakarta ORO regular expression engine that is used in ColdFusion. reMatch/reMatchNoCase are terrible when it comes to capturing. Java on the other hand offers the POSIX regular expression engine.
<cfset data = [
"Log-Date: 10/26/2012. Record created. Admission Date: 08/01/2012
Log-Date: 06/20/2013 Discharged. Discharge Date:10/15/2012
Reason for Discharge:01 - (routine discharge).
More stuff...",
"Log-Date: 10/26/2012. Record created. Admission Date: 08/01/2012
Log-Date: 06/20/2013 Discharged. Discharge Date:10/16/2012
Reason for Discharge:lorem ipsum."
]>
<cfset result = queryNew("DISCHARGE_DATE,DISCHARGE_REASON", "VARCHAR,VARCHAR")>
<cfloop array="#data#" index="line">
<cfset dischargeDate = reMatchGroupNoCase("Discharge Date:([0-9]{2}/[0-9]{2}/[0-9]{4})", line)>
<cfset dischargeReason = reMatchGroupNoCase("Reason for Discharge:([^\n]*)", line)>
<cfset hasDate = (arrayLen(dischargeDate) eq 1)>
<cfset hasReason = (arrayLen(dischargeReason) eq 1)>
<cfif hasDate or hasReason>
<cfset rowIndex = queryAddRow(result, 1)>
<cfif hasDate and isDate(dischargeDate[1])>
<cfset querySetCell(result, "DISCHARGE_DATE", dateFormat(dischargeDate[1], "yyyy-mm-dd"), rowIndex)>
</cfif>
<cfif hasReason>
<cfset querySetCell(result, "DISCHARGE_REASON", dischargeReason[1], rowIndex)>
</cfif>
</cfif>
</cfloop>
<cfquery name="orderedResult" dbType="query">
SELECT
*
FROM
[result]
ORDER BY
[DISCHARGE_DATE] ASC
</cfquery>
<cfdump var="#orderedResult#">
And here is the function you need:
<cffunction name="reMatchGroupNoCase" access="public" output="false" returnType="array">
<cfargument name="regex" type="string" required="true">
<cfargument name="value" type="string" required="true">
<cfset LOCAL.result = []>
<cfset LOCAL.Pattern = createObject("java", "java.util.regex.Pattern")>
<cfset ARGUMENTS.regex = LOCAL.Pattern.compile(ARGUMENTS.regex, bitOr(LOCAL.Pattern["CASE_INSENSITIVE"], LOCAL.Pattern["UNICODE_CASE"]))>
<cfset LOCAL.buffer = ARGUMENTS.regex.matcher(toString(ARGUMENTS.value))>
<cfset LOCAL.length = LOCAL.buffer.groupCount()>
<cfloop condition="LOCAL.buffer.find()">
<cfloop from="1" to="#LOCAL.length#" index="LOCAL.i">
<cfset LOCAL.value = LOCAL.buffer.group(
javaCast("int", LOCAL.i)
)>
<cfif isNull(LOCAL.value)>
<cfcontinue>
</cfif>
<cfset LOCAL.result.add(LOCAL.value)>
</cfloop>
</cfloop>
<cfreturn LOCAL.result>
</cffunction>
I recommend this approach:
with q1 as (select 'Log-Date: 10/26/2012. Record created. Admission Date: 08/01/2012
Log-Date: 06/20/2013 Discharged. Discharge Date:10/15/2012
Reason for Discharge:01 - (routine discharge). ' logData
)
select substring(logData, patindex('%Admission Date: %', logdata) + 16
, 10) admitDate
from q1
where logData like '%Discharge Date:%'
That returns 08/01/2012. You may have some complications for a variety of reasons, but the general idea should work.
I am getting an error after upgrade from coldfusionOX to coldfusion 10.
Error Occurred While Processing Request Complex object types cannot be
converted to simple values.
The expression has requested a variable or an intermediate expression
result as a simple value. However, the result cannot be converted to a
simple value. Simple values are strings, numbers, boolean values, and
date/time values. Queries, arrays, and COM objects are examples of
complex values. The most likely cause of the error is that you tried
to use a complex value as a simple one. For example, you tried to use
a query variable in a cfif tag.
It occurs at line " cfloop index="local.thisRight" list="#rights#" ". It seems like ColdFusion does not like the "rights" here.
Anyone can give me some help? Thanks so much.
<cfif local.profile.rights.profile.self is not "">
<cfquery name="local.getAffiliations" datasource="#Request.readerDSN#">
SELECT tblPersonsToAffiliations.affiliationID, tblPersonsToAffiliations.rights, tblAffiliations.affiliationType, tblPersonsToAffiliations.relationshipType
FROM tblPersonsToAffiliations INNER JOIN tblAffiliations
ON tblPersonsToAffiliations.affiliationID = tblAffiliations.affiliationID
WHERE tblPersonsToAffiliations.personID IN (#local.profile.rights.profile.self#)
AND (tblPersonsToAffiliations.archived IS NULL
OR tblPersonsToAffiliations.archived = '')
</cfquery>
<cfif local.getAffiliations.recordCount is not 0>
<cfloop query="local.getAffiliations">
<cfif local.getAffiliations.relationshipType is "interested">
<cfset local.thisRelationshipType = "provisionalMember">
<cfif IsDefined("local.profile.rights.#affiliationType#.#local.thisRelationshipType#")>
<cfset local.profile.rights[affiliationType][local.thisRelationshipType] = ListAppend(local.profile.rights[affiliationType][local.thisRelationshipType], affiliationID)>
<cfelse>
<cfset local.profile.rights[affiliationType][thisRelationshipType] = affiliationID>
</cfif>
<cfelse>
<cfset local.thisRelationshipType = "fullMember">
<cfif IsDefined("local.profile.rights.#affiliationType#.#local.thisRelationshipType#")>
<cfset local.profile.rights[affiliationType][local.thisRelationshipType] = ListAppend(local.profile.rights[affiliationType][local.thisRelationshipType], affiliationID)>
<cfelse>
<cfset local.profile.rights[affiliationType][local.thisRelationshipType] = affiliationID>
</cfif>
<cfif isNull(rights)>
<cfelse>
<cfloop index="local.thisRight" list="#rights#" >
<cfif IsDefined("local.profile.rights.#affiliationType#.#local.thisRight#")>
<cfset local.profile.rights[affiliationType][local.thisRight] = ListAppend(local.profile.rights[affiliationType][local.thisRight], affiliationID)>
<cfelse>
<cfset local.profile.rights[affiliationType][local.thisRight] = affiliationID>
</cfif>
</cfloop>
</cfif>
</cfif>
</cfloop>
</cfif>
</cfif>
A bit earlier in your code you do this:
<cfif local.getAffiliations.relationshipType is "interested">
I think you need the same query name prefix in front of "rights" that is used when evaluating "relationshipType".
Try this:
#local.getAffiliations.rights#
HTH!
I am betting it is failing on this line:
<cfloop index="local.thisRight" list="rights" >
You are attempting to use the string "rights" as a list. My first reaction would be that you need to make that:
<cfloop index="local.thisRight" list="#rights#" >
I am creating a INSERT Starement for my table. Till now all going good and i have been able to create the Insert Statement. Only Issue Left is: It shows a trailing comma after the end of every single record. Can you guys have a look around what mess I am doing here
<cfset listcount = getQueryColumns(insertData)>
<cfset counter = 1>
<cfloop query="insertData">
<cfoutput>
INSERT INTO `mytable` (#listcount#)
VALUES(
<cfloop index="col" list="#listcount#">'#insertData[col][currentRow]#'
<cfif counter LT insertData.recordcount>,</cfif>
</cfloop>);<br><br>
</cfoutput>
<cfset counter++>
</cfloop>
Your error is due to the fact that you are incrementing your counter in the outer loop instead of the inner loop.
I think I've got it. I believe this is what you need:
<cfset listcount = getQueryColumns(insertData)>
<cfloop query="insertData">
<cfset counter = 1>
<cfoutput>
INSERT INTO `mytable` (#listcount#)
VALUES(
<cfloop index="col" list="#listcount#">'#insertData[col][currentRow]#'
<cfif counter LT listcount>,</cfif>
<cfset counter++>
</cfloop>);<br><br>
</cfoutput>
</cfloop>
What I changed is:
As Dan Bracuk pointed out, I moved <cfset counter++> inside the inner loop. I also moved <cfset counter = 1> inside the outer loop, as it will need to be reinitialized through successive INSERT statements.
I changed <cfif counter LT insertData.recordcount> to <cfif counter LT listcount>, as you don't want to iterate over the recordcount (this is why your commas stopped appearing after Priority, which was the 8th field). Instead, you want to iterate over the number of columns.
EDIT: See my more recent answer. I'm leaving this one in place because the comments were useful in the diagnosis.
I think Dan Bracuk is correct about your counter increment. But you might be able to simplify your code and avoid the <cfif > statement entirely if you you use the list attribute in <cfqueryparam >. For example:
<cfqueryparam value="#NAME_OF_LIST#" list="yes" >
By default this will put a comma between your list values before sending them to the database.
Check out the other attributes it takes at http://www.cfquickdocs.com/cf8/#cfqueryparam.
I have a simple cfquery which outputs 3 columns with their respective data. The columns are name, address and age.
I want to transpose this set of data so that the names become the columns and the address and age are displayed under each column.
I know that we can use QueryAddColumn or something like this for this issue. Can someone help me out with this problem?
EDIT:
Based on the comment below this is the intended output:
Oct 2011 Nov 2011 Dec 2011 Jan 2012 Feb 2012
NumberofPeople NumberofPeople NumberofPeople NumberofPeople NumberofPeople
EmploymentRate EmploymentRate EmploymentRate EmploymentRate EmploymentRate
I have included a sample data row at the top where you would put your cfquery statement.
<cfset firstQuery = queryNew("date,NumberofPeople,EmploymentRate")>
<cfset aRow = queryAddRow(firstQuery)>
<cfset querySetCell(firstQuery,"date","OCT_2011",aRow)>
<cfset querySetCell(firstQuery,"NumberofPeople","28",aRow)>
<cfset querySetCell(firstQuery,"EmploymentRate","50%",aRow)>
<cfset aRow = queryAddRow(firstQuery)>
<cfset querySetCell(firstQuery,"date","NOV_2011",aRow)>
<cfset querySetCell(firstQuery,"NumberofPeople","28",aRow)>
<cfset querySetCell(firstQuery,"EmploymentRate","56%",aRow)>
<cfset aRow = queryAddRow(firstQuery)>
<cfset querySetCell(firstQuery,"date","DEC_2011",aRow)>
<cfset querySetCell(firstQuery,"NumberofPeople","29",aRow)>
<cfset querySetCell(firstQuery,"EmploymentRate","55%",aRow)>
<cfset aRow = queryAddRow(firstQuery)>
<cfset querySetCell(firstQuery,"date","JAN_2012",aRow)>
<cfset querySetCell(firstQuery,"NumberofPeople","30",aRow)>
<cfset querySetCell(firstQuery,"EmploymentRate","52%",aRow)>
<!--- Will Create new query with names as column headers--->
<cfset newQuery = queryNew(valueList(firstQuery.date,','))>
<!--- Will Create new query with names as column headers--->
<cfset people = queryAddRow(newQuery)>
<cfset rate = queryAddRow(newQuery)>
<cfloop query='firstQuery'>
<!---Syntax for this function is: QuerySetCell(query, column_name, value [, row_number ]) --->
<cfset querySetCell(newQuery,firstQuery.date,firstQuery.NumberofPeople,people)>
<cfset querySetCell(newQuery,firstQuery.date,firstQuery.EmploymentRate,rate)>
</cfloop>
<cfdump var="#newQuery#">
<cfdump var="#ArrayToList(newQuery.getColumnNames())#">
This is How I would Do it, But I can't think of why I would do it. I'd be interested to hear your use case. Anyway, I hope this helps.
(P.S This is tested in CF9, so you should be able to copy and paste it to test for yourself.)
EDIT -(Again):
Forgot to mention, this can only work if the names your retrieveing from the DB are valid column names, so no spaces (In this example spaces in dates have been replaced by underscores)!
>>> New code snippet for the updated data structure, the function valueList(firstQuery.date,',') doesn't re-order your columns. The columns are re-ordered on output when dumping. I have used the function ArrayToList(newQuery.getColumnNames()) to show that internally CF maintains the column order and you need only ask it nicely. You should be able to use all this information to nicely output your data how you need it.
Maybe I'm missing something but it seems like a simple SQL query with the ORDER BY clause would work. Something like this:
<cfquery name="myquery" datasource="yourdatasourcename">
select name, address, age
from tablename
order by name
</cfquery>
Then in your ColdFusion output page, you can use the tag with the group attribute. Something like this:
<cfoutput query="myquery">
<p>name = #name#
<cfoutput group="name">
age = #age#
address = #address#<br />
</cfoutput>
</p>
</cfoutput>
Obviously, you can format the output however you wish.
EDIT --
If you are wanting to display like:
Mary Joe Sam Suzie
28 36 25 42
123 Maple 16 Oak 3723 Street 832 Busy St.
Perhaps something like (I have not tested this, just brainstorming):
<cfoutput query="myquery" group="name">
<div style="float:left;">name = #name#
<cfoutput>
<p>
age = #age#<br />
address = #address#
</p>
</cfoutput>
</div>
</cfoutput>
I think you are describing a pivot query in SQL.