Transpose query in ColdFusion - coldfusion

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.

Related

ColdFusion list value replacement

I have a set of list values in ColdFusion variable, and I need to replace all the list values into desired text.
For Example:
<cfset headerColumnList = "FirstName,LastName,Email,FrequentGuestID,IP Address,Time Stamp Email Marketing">
<cfset a="test1">
<cfset b="test2">
<cfset c="test3">
<cfset d="test4">
<cfset e="test5">
<cfset f="test6">
<cfloop index = "ListElement" list= "#headerColumnList#" delimiters = ",">
<cfoutput>
#replaceList("#ListElement#","FirstName,LastName,Email,FrequentGuestID,IP Address,Time Stamp Email Marketing","#a#,#b#,#c#,#d#,#e#,#f#",",")#
</cfoutput>
</cfloop>
Output:
test1
test2
test3
test4
test5
Time Stamp test3 Marketing
In the above scenario. The value "Time Stamp Email Marketing" is supposed to be replaced with "test6" but I am getting in an alternative way where it is not replacing the phrase as a whole word. Can anyone tell me how do I replace the list phrases, any alternative for this?
Here you can use the ListQualify function to get exact result of an your scenario. So convert it in to qualify values and looping with that then you can replace it with your own list data. No need to change any order of a list values.
<cfset quoted = listQualify(headerColumnList,"''")>
<cfloop index = "ListElement" list= "#quoted#" delimiters = ",">
#replaceList(ListElement,quoted,"#a#,#b#,#c#,#d#,#e#,#f#")#
<br/>
</cfloop>
The code is working as written. You are seeing this because your check for "Email" in the replaceList() function is firing before the check for "Time Stamp Email Marketing". Notice the word "Email" in that string.
I don't know what your actual use case is but you can change the order of your code for this specific example to make it work like you want.
<cfset headerColumnList = "FirstName,LastName,Email,FrequentGuestID,IP Address,Time Stamp Email Marketing">
<cfset a="test1">
<cfset b="test2">
<cfset c="test3">
<cfset d="test4">
<cfset e="test5">
<cfset f="test6">
<cfloop index = "ListElement" list= "#headerColumnList#" delimiters = ",">
<cfoutput>
#replaceList("#ListElement#","FirstName,LastName,FrequentGuestID,IP Address,Time Stamp Email Marketing,Email","#a#,#b#,#d#,#e#,#f#,#c#",",")#
</cfoutput>
</cfloop>
This gives the desired output. Notice how I reordered the conditions within the replaceList() function.

ColdFusion Sorting/Assignment

I have a two lists: One that is dynamic, based off of a recordcount of students and the other is the students..i.e., 001,002,003, etc. and 123456 (student data). I need some help being able to randomly assign students one of those numbers. For example, if I have 5 students (123456,234561, etc.), I need to be able to randomly assign 001,002, etc. to those students. So far, hitting a wall. The following is what I have so far:
<cfquery name="testjd" datasource="student">
SELECT SoonerID FROM dbo.CurrentStudentData
WHERE status = 'Student' OR status = 'JD'
</cfquery>
<cfset testList = valueList(testjd.soonerid)>
<cfset totalRecordsJd = #testjd.recordcount#>
<cfloop from="001" to="#totalRecordsJd#" index="i">
<cfset examNo = i>
<cfif len(i) is 1>
<cfset examNo = "00" & i>
<cfelseif len(i) is 2>
<cfset examNo = "0" & i>
</cfif>
<cfif not listFind(usedJDExams, examNo)>
#examNo#<!---is NOT being used!---><br/>
</cfif>
</cfloop>
CF9 makes it a little less fun than later versions. I believe this should work (except for my query mockup).
https://trycf.com/gist/3667b4a650efe702981cb934cd325b08/acf?theme=monokai
First, I create the fake query.
<!---
Simple faked up query data. This is just demo data. I think this
queryNew() syntax was first available in CF10.
--->
<cfscript>
testjd = queryNew("SoonerID", "varchar", [
["123456"],
["564798"],
["147258"],
["369741"]
]);
</cfscript>
Now that I've got a list of students who need tests, I create an array of numbers for those tests.
<!--- Create array of Available Exam Numbers --->
<cfset examNos = ArrayNew(1)>
<cfloop from=1 to=100 index="i">
<cfset examNos[i] = right('00' & i,3)>
</cfloop>
We now combine the two sets of data to get the Exam Numbers assigned to the Student.
<!--- Loop through the query and build random assignments --->
<cfloop query="#testjd#">
<!---Get random exam no.--->
<cfset examNo = examNos[randrange(1,arrayLen(examNos))]>
<!---Build struct of exam assignments--->
<cfset testAssignments[SoonerID] = examNo>
<!---Delete that num from exam array. No reuse.--->
<cfset blah = arrayDelete(examNos,examNo)>
</cfloop>
And this gives us
<cfoutput>
<cfloop collection="#testAssignments#" item="i">
For User #i#, the test is #testAssignments[i]#.<br>
</cfloop>
</cfoutput>
The unused tests are: <cfoutput>#ArrayToList(examNos)#</cfoutput>.
--------------------------------------------------------------------
For User 369741, the test is 054.
For User 147258, the test is 080.
For User 564798, the test is 066.
For User 123456, the test is 005.
The unused tests are:
001,002,003,004,006,007,008,009,010
,011,012,013,014,015,016,017,018,019,020
,021,022,023,024,025,026,027,028,029,030
,031,032,033,034,035,036,037,038,039,040
,041,042,043,044,045,046,047,048,049,050
,051,052,053,055,056,057,058,059,060
,061,062,063,064,065,067,068,069,070
,071,072,073,074,075,076,077,078,079
,081,082,083,084,085,086,087,088,089,090
,091,092,093,094,095,096,097,098,099,100.
A couple of code review notes for the OP code:
1) It's easier to work with arrays or structures than it is to work with a list.
2) cfloop from="001" to="#totalRecordsJd#": from "001" is a string that you are comparing to an integer. ColdFusion will convert "001" to a number in the background, so that it can actually start the loop. Watch out for expected data types, and make sure you use arguments as they were intended to be used.
3) cfif len(i) is 1...: First, it's less processing to build this string in one pass and them trim it - right('00' & i,3). Second (and this is a personal nitpick), is and eq do essentially the same thing, but I've always found it good practice to apply is to string-ish things and eq to number-ish things.
=====================================================================
For CF10+, I would use something like
https://trycf.com/gist/82694ff715fecd328c129b255c809183/acf2016?theme=monokai
<cfscript>
// Create array of random string assignments for ExamNo
examNos = [] ;
for(i=1; i lte 100;i++) {
arrayAppend(examNos,right('00'& i,3)) ;
}
///// Now do the work. ////
//Create a struct to hold final results
testAssignments = {} ;
// Loop through the query and build random assignments
for(row in testjd) {
// Get random exam no.
examNo = examNos[randrange(1,arrayLen(examNos))] ;
// Build struct of exam assignments
structInsert(testAssignments, row.SoonerID, examNo) ;
// Delete that num from exam array. No reuse.
arrayDelete(examNos,examNo) ;
}
</cfscript>
If it is a small query, why not just sort the records (psuedo) randomly using NEWID()? Since the records will already be randomized, you cna use query.currentRow to build the "examNo".
<cfquery name="testjd" datasource="student">
SELECT SoonerID
FROM CurrentStudentData
WHERE status IN ('Student', 'JD')
ORDER BY NewID()
</cfquery>
<cfoutput query="yourQuery">
#yourQuery.SoonerID# #NumberFormat(yourQuery.currentRow, "000000")#<br>
</cfoutput>
This is a formatted comment. After you run this query:
<cfquery name="testjd" datasource="student">
SELECT SoonerID FROM dbo.CurrentStudentData
WHERE status = 'Student' OR status = 'JD'
</cfquery>
Do this:
<cfset QueryAddColumn(testJd, "newcolumn", arrayNew(1))>
Then loop through the queries and assign values to the new column with QuerySetCell.

Create a comma separated list of quoted values

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>

CFLoop and ListValueCount

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>

ColdFusion: Can you pull out a unique record from a query using recordCount?

It's a bit of tricky question, however, my page for most rated bands displays the band logos in order of how high they have been rated. My only problem is i want to count through the records by using a cfloop from 1 to 10 and because it is split in to two columns, have one counting 1 through to 9 and the other 2 through to 10, each of them with steps of two.
Can anybody help me with this? If i've confused just mention it and ill try to clarify exactly what i mean.
<DIV class="community_middle">
<cfoutput query="top10MostRated">
<cfloop from="2" to="10" index="i" step="2">
<DIV class="communityContent">
#chr(i)#
<IMG src="logo/#top10MostRated.Logo#" alt="#top10MostRated.Name#" width="100%" height="100%"></IMG>
</DIV>
<BR/>
</cfloop>
</cfoutput>
</DIV>
If you're looking to do odd/even lists separately, then you can use the currentrow property of the query combined with the modulo operator (%) to work out if the row is odd or even:
<cfloop query="topBands>
<cfif topBands.currentRow % 2 = 1>
<!--- do your odd number output here --->
</cfif>
</cfloop>
<cfloop query="topBands>
<cfif topBands.currentRow % 2 = 0>
<!--- do your even number output here --->
</cfif>
</cfloop>
I think these answers address your side-by-side part of your question but does not explain the "same image" issue. Their code is written correctly but does not explain the reason.
Your code:
<IMG src="logo/#top10MostRated.Logo#"
alt="#top10MostRated.Name#"
width="100%" height="100%"></IMG>
... would be fine if you were only inside a <cfloop query = "top10MostRated"> or <cfoutput query = "top10MostRated"> block. The reason is because inside these types of blocks CF is smart enough to know you want the data for the current row. It would be the same as:
<IMG src="logo/#top10MostRated.Logo[top10MostRated.currentRow]#"
alt="#top10MostRated.Name[top10MostRated.currentRow]#"
width="100%" height="100%" />
Because you're nesting the to/from cfloop inside a <cfoutput query = ""> block, you are getting unexpected results. Your existing code is always asking for the record provided by your outer loop. Hence you see the same image 5 times. (using any of the fine examples provided will help you get out of this) but, you can remove the query from your cfoutput and simply ask CF to show you the value for the correct row in your loop using your index (you set your index to "i") so the below would show you the image that corresponds to your loop.
<IMG src="logo/#top10MostRated.Logo[i]#"
alt="#top10MostRated.Name[i]#"
width="100%" height="100%" />
It sounds like what you'd like to get is a collection of even-numbered records and a collection of odd-numbered records. In Coldfusion 10 or Railo 4, you can use groupBy() from Underscore.cfc to split up your query result into manageable sub-sets, like so:
_ = new Underscore();// instantiate the library
groupedBands = _.groupBy(topBands, function (val, index) {
return index % 2 ? "odd" : "even";
});
This returns a struct with two elements odd and even, each containing an array of records which are odd or even. Example result:
{
odd: [{name: "Band one"}, {name: "Band three"}],
even: [{name: "Band two"}, {name: "Band four"}]
}
Splitting your results into logical sub-sets makes the code more readable:
<cfoutput>
<cfloop from="1" to="5" index="i">
<div class="left">#groupedBands.odd[i].name#</div>
<div class="right">#groupedBands.even[i].name#</div>
</cfloop>
</cfoutput>
You'll also be able to use those sub-sets in other places on your page if you need to.
Note: I wrote Underscore.cfc
Ben Nadel has a post exactly for this. Link here
A breakdown for this is
<cfloop query="top10MostRated">
<cfif top10MostRated.CurrentRow MOD 2>
<!--- Add to the "odd list" --->
<cfelse>
<!--- Add the record to the "even list" --->
</cfif>
</cfloop>
Then you'll have 2 lists oddList and evenList. Then it's just a matter of displaying them.
I'd do it a different way. The objective is to have records 1 and 2 side by side and I don't see that in #barnyr's answer.
<cfoutput>
<cfloop from="2" to="topbands.recordcount + 1" index = "i" step="2">
#topbands.fieldname[i-1]#
<cfif i lte topbands.recordcount>
#topbands.fieldname[i]# <br />
</cfif>
</cfloop>
</cfoutput>