"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" SQL TIP: TALLY MULTIPLE COLUMNS & SAVE THE RESULT """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" PRODUCT : R:BASE VERSION : 3.1 CATEGORY : SQL SUBCATEGORY : TALLY """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Replace programs, complex reports, and relational commands with SQL to achieve maximum performance. To count the occurrences of multiple columns, use the SELECT function COUNT. It counts the number of rows in each group of columns specified in the GROUP BY clause. Here's an example using CONCOMP: SELECT empcity, empstate, COUNT(*) + FROM employee + GROUP BY empcity, empstate The result is a chart like this: empcity empstate COUNT(*) ------------ ------------- -------- Duvall WA 1 Redmond WA 2 Seattle WA 4 Woodinville WA 1 Multi-column, Multi-table Tally """"""""""""""""""""""""""""""" You can have both multiple columns and multiple tables in your counts. The WHERE clause links the tables by specifying the linking columns, and COUNT counts the rows in each group specified in the GROUP BY clause. The chart might look like this: t2.emplname t1.empid t2.empstate SUM(t1.bonus) COUNT(*) ----------- -------- ----------- ------------- -------- Wilson 102 WA $743.50 4 Hernandez 129 WA $302.73 3 Smith 131 WA $940.50 3 Coffin 133 WA $27.00 1 Simpson 160 WA $631.88 2 This chart was produced by using the CONCOMP database that comes with R:BASE. It shows that you can set up the count and include extra information like a sum for each group. The following SELECT command counts the employee name (EMPLNAME), state (EMPSTATE), and identification number (EMPID) and includes the total and number of their bonuses: SELECT t2.emplname, t1.empid, + t2.empstate, SUM(t1.bonus), COUNT(*) + FROM salesbonus T1, employee T2 + WHERE (t1.empid = t2.empid) + GROUP BY + t2.empstate, t1.empid, t2.emplname Display Only If More Than One """"""""""""""""""""""""""""" Sometimes you may want to tally a group of columns and show only those groups where the count is more than one. You can do this by adding a HAVING clause to limit the groups displayed. A HAVING clause limits the groups selected by a GROUP BY clause in much the same way a WHERE clause limits the rows selected by a command. The following CONCOMP example shows how to use the HAVING clause to limit groups: SELECT empcity, empstate, COUNT(*) + FROM employee + GROUP BY empcity, empstate + HAVING COUNT(*) > 1 The result is a chart like this: empcity empstate COUNT(*) ------------ ------------- -------- Redmond WA 2 Seattle WA 4 Save Tallies in a View or Table """"""""""""""""""""""""""""""" To save tallies in a view, use SELECT with CREATE VIEW. To save tallies in a table, create a table to hold the tallies; then use SELECT with INSERT.