Jump to content
Sign in to follow this  
Eminence

Selecting and Counting Specific Columns

Recommended Posts

Hello,

Using SQLite, I was trying to select a specific column with having duplicate entries removed by using the DISTINCT function. 

Local $sQuery = "SELECT DISTINCT supervisor, COUNT(DISTINCT employee_name) FROM data_db

What the above snippet does is just list only one supervisor but with the total count of unique employee names in the whole database when it should be listing out all supervisor entries from the database and list the total count of employees per each supervisors. If I remove the COUNT function, it does list out all unique entries of supervisor names from the list. Attached is a screenshot of an example database as well. 

Any help will be much appreciated. Thank you!

database_sample.png

Share this post


Link to post
Share on other sites
3 hours ago, Danp2 said:

A typical SQL Select statement would look like this --

SELECT  supervisor, COUNT(DISTINCT employee_name) FROM your_db GROUP BY supervisor

 

There we go. Thanks a bunch! :)

Share this post


Link to post
Share on other sites

Now I'm trying to count the number of employees per supervisor that has the attendance_status of Absent using this query.

Local $sQuery = "SELECT DISTINCT supervisor, COUNT(DISTINCT employee_name), COUNT(attendance_status) FROM data_db WHERE attendance_status = 'ABSENT' GROUP BY supevisor"

But what it does is it also affects the second row(total count of the employees name) only showing employees that has the tagging of absent when I just want it to affect the third column. 

Edited by Eminence

Share this post


Link to post
Share on other sites

Just another quick question related to this, do I need to have a separated column in the database if I want to calculate the difference of the count of the total employees' schedule status tagged as work and the count of the total employees' attendance status tagged as absent?

What I want to do is calculate the absenteeism rate per supervisor based on the formula above however, I don' have a column for the absenteeism rate.

Share this post


Link to post
Share on other sites

Below is my current SQL statement. I'm still figuring out how to calculate the percentage of the total count of scheduled vs absent employees though.

Local $sQuery = "SELECT DISTINCT supervisor, COUNT(DISTINCT employee_name), COUNT(CASE WHEN attendance_status LIKE 'ABSENT' THEN 1 END) AS count1, COUNT(CASE WHEN late_hours > 0.00 THEN 1 END) AS count1 FROM data_db WHERE supervisor != '' GROUP BY supervisor"

 

Share this post


Link to post
Share on other sites

You have two different fields named 'count1'. Not sure what's up with that. I would try something like this --

Local $sQuery = "SELECT DISTINCT supervisor, COUNT(DISTINCT employee_name) as emp_count, COUNT(CASE WHEN attendance_status LIKE 'ABSENT' THEN 1 END) AS abs_count, COUNT(CASE WHEN late_hours > 0.00 THEN 1 END) AS late_count, abs_count / emp_count * 100 AS abs_rate FROM data_db WHERE supervisor != '' GROUP BY supervisor"

 

Share this post


Link to post
Share on other sites
2 hours ago, Danp2 said:

You have two different fields named 'count1'. Not sure what's up with that. I would try something like this --

Local $sQuery = "SELECT DISTINCT supervisor, COUNT(DISTINCT employee_name) as emp_count, COUNT(CASE WHEN attendance_status LIKE 'ABSENT' THEN 1 END) AS abs_count, COUNT(CASE WHEN late_hours > 0.00 THEN 1 END) AS late_count, abs_count / emp_count * 100 AS abs_rate FROM data_db WHERE supervisor != '' GROUP BY supervisor"

 

 

Thanks @Danp2. After running, it says no such column: abs_count, do I also have to create a column for abs_count in SQLite instead? 

Share this post


Link to post
Share on other sites
3 hours ago, Danp2 said:

Not sure how to advise you from here. I believe the syntax I posted is correct. However, it's possible that SQLite doesn't support it.

 

Could be. I'll look into it. Thanks again @Danp2:)

Share this post


Link to post
Share on other sites

There is very little limit on the complexity of SQL requests in SQLite.

What remains unclear is the actual DB schema, the semantics of every column and the meaning of the data stored there.
Post the schema and a sample data so that we can build a request satisfying your requirements. Be as clear and formal as possible.

 


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites
2 hours ago, jchd said:

There is very little limit on the complexity of SQL requests in SQLite.

What remains unclear is the actual DB schema, the semantics of every column and the meaning of the data stored there.
Post the schema and a sample data so that we can build a request satisfying your requirements. Be as clear and formal as possible.

 

Here's what I have

 

database_sample.png

Edited by Eminence
Corrected database screenshot

Share this post


Link to post
Share on other sites

I don't get it. This isn't the schema (list of all DDL statements). Please list all "CREATE TABLE ..." statements.

What's the column "attendance_status" you're basing your request on?


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites
CREATE TABLE data_db (
    id                      INTEGER PRIMARY KEY AUTOINCREMENT,
    employee_number         STRING,
    employee_name           STRING,
    supervisor              STRING,
    date                    DATETIME,
    schedule_status         STRING,
    attendance_status       STRING,
    operational_minutes     STRING,
    late_hours              STRING
);

My bad. Here's the DDL. The data comes from a .CSV file generated from an internal web application.

So I'm trying to count the total number of employees' schedule_status tagged as WORK and their attendance_status tagged as ABSENT and from there, calculate the Abs. Rate %. 

Edited by Eminence

Share this post


Link to post
Share on other sites

So I tried this:

Dividing count of attendance_status tagged with absent over the count of shedule_status tagged with work.

Local $sQuery = "SELECT DISTINCT supervisor, COUNT(DISTINCT employee_name) as emp_count, COUNT(CASE WHEN attendance_status LIKE 'ABSENT' THEN 1 END) AS abs_count, COUNT(CASE WHEN late_hours > 0.00 THEN 1 END) AS late_count, (COUNT(CASE WHEN attendance_status IS 'ABSENT' THEN 1 END) / COUNT(CASE WHEN schedule_status IS 'WORK' THEN 1 END) * 100) FROM data_db WHERE supervisor != '' GROUP BY supervisor"

It does return a value of 0 though, whereas changing the order to schedule_status over the count of attendance_status it does return a different result. Any ideas?

Share this post


Link to post
Share on other sites

Ok I believe I get the picture, more or less.

First there are some problems with your table design.

1) SQLite doesn't have datatypes STRING nor DATETIME. Those columns are parsed as being unknown datatypes with affinity BLOB. Probably not what you intended.
2) "operational_minutes" should probably call "operational_hours"
3) Both "operational_minutes" and "late_hours" should be REAL, not STRING (nor TEXT).
4) You can't make further use of result columns aliased. That's why "abs_count" is unknown.
5) You probably don't need to use "autoincrement" for the id primary key. That doesn't mean what you think it means.

To fix this I defined a table like this:

CREATE TABLE "data_db" (
  "id" INTEGER PRIMARY KEY,
  "employee_number" TEXT,
  "employee_name" TEXT,
  "supervisor" TEXT,
  "date" TEXT,
  "schedule_status" TEXT,
  "attendance_status" TEXT,
  "operational_hours" REAL,
  "late_hours" REAL);

I had to type (you pasted a picture) some random data in:

id  employee_number employee_name supervisor    date       schedule_status attendance_status operational_hours late_hours
1   100123          John Doe      Bryan McGrath 2018-08-09 WORK            WORK                           7.47       1.55
2   100124          Jane Doe      Bryan McGrath 2018-08-09 WORK            ABSENT                            0          0
3   178223          Joe Grifith   Neil Grant    2018-08-09 WORK            WORK                              8          0
4   182123          Ryan Banks    Summer Harley 2018-08-09 WORK            ABSENT                            0          0
5   143708          Paul Tanner   Summer Harley 2018-08-08 WORK            WORK                           7.15       0.34
6   075891          Bill Moots    Neil Grant    2018-08-09 WORK            WORK                           8.12          0
7   000156          Shirley Vroot Neil Grant    2018-08-07 WORK            ABSENT                            0          0
8   000163          Shirley Wok   Neil Grant    2018-08-07 WORK            WORK                           7.52          0
9   542980          Dan Vroot     Neil Grant    2018-08-07 WORK            WORK                           6.45          0
10  514802          Sheila Vroot  Neil Grant    2018-08-07 WORK            WORK                           8.33       1.06


Then this statement should be close to what you want:
SELECT
  supervisor,
  COUNT(employee_name) emp_count,
  SUM(CASE WHEN attendance_status LIKE 'ABSENT' THEN 1 else 0 END) abs_count,
  SUM(CASE WHEN late_hours > 0 THEN 1 else 0 END) late_count,
  printf('%2.2f', 100.0 * SUM(CASE WHEN attendance_status LIKE 'ABSENT' THEN 1 else 0 END) / COUNT(employee_name)) abs_rate
FROM
  data_db
WHERE supervisor != ''
GROUP BY supervisor

The result then is:

supervisor      emp_count   abs_count   late_count  abs_rate
Bryan McGrath           2           1            1     50.00
Neil Grant              6           1            1     16.67
Summer Harley           2           1            1     50.00

Note that your DB currently contains text instead of numeric values.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Jahar
      I have an AutoIT script It monitors 2 websites for content that applys to me and the services that I provide. One site is : www.Freelancer.com The other: www.PeoplePerHour.com Both sites publish new jobs on their site hourly or so. My AutoIT app, will view those sites and present new jobs to me in a grid that pops up on my screen. Lately, the app has stopped showing me any jobs from PeoplePerHour.
       
      For freelancer.com,  Inetget is giving full html but for peopleperhour, now its not coming.
      Func _CheckPPH()
          Local Static $hTimer = 0
          Local Static $hDownload = 0
          Local $aTitlesandUrls = 0
          Local Static $sTempFile = ""
          If $hTimer = 0 Then $hTimer = TimerInit()
          If $hDownload = 0 Then
              $sTempFile = _WinAPI_GetTempFileName(@TempDir)
              ConsoleWrite("Checking PPH..." & @CRLF)
              ConsoleWrite(">Downloading..." & @CRLF)
      ;~         $hDownload = InetGet("http://www.peopleperhour.com/freelance-jobs", $sTempFile, $INET_FORCERELOAD, $INET_DOWNLOADBACKGROUND)
              $hDownload = InetGet("http://www.peopleperhour.com/freelance-jobs", $sTempFile, $INET_FORCERELOAD)
      ;~         Return 0
          EndIf
      ;~     Sleep(30)
      ;~     Local $isCompleted = InetGetInfo($hDownload, $INET_DOWNLOADCOMPLETE)
      ;~     Local $isError = InetGetInfo($hDownload, $INET_DOWNLOADERROR)
      ;~     Sleep(30)
      ;~     If TimerDiff($hTimer) > 3000 And $isError Then
      ;~         ConsoleWrite("!PPH Fail" & @CRLF)
      ;~         InetClose($hDownload)
      ;~         $hDownload = 0
      ;~         Return 0
      ;~     EndIf
      ;~     Sleep(30)
          Local $Show = 0
      ;~     If TimerDiff($hTimer) > 3000 And $isCompleted Then
          If $hDownload > 0 Then
              ConsoleWrite("+Downloaded..." & @CRLF)
              Local $sPPHHtml = FileRead($sTempFile)
              $aTitlesandUrls = _StringBetween($sPPHHtml, '"title">' & @LF, 'time>')
      ;~         _ArrayDisplay($aTitlesandUrls)
              Local $aPPH[0][4]
              Local $sTitle = ""
              Local $sUrl = ""
              Local $sID = ""
              Local $sDate = ""
              Local $iRet=0
              Sleep(30)
              For $i = 0 To UBound($aTitlesandUrls) - 1
                  $sTitle = _StringBetween($aTitlesandUrls[$i], '<a title="', '" class')
                  $sUrl = _StringBetween($aTitlesandUrls[$i], 'href="', '">')
                  $sDate = _GetDate($aTitlesandUrls[$i])
                  If IsArray($sTitle) And IsArray($sUrl) Then
                      $sID = _GetID($sUrl[0])
      ;~                 _ArrayAdd($aPPH, $sDate & "|" & $sTitle[0] & "|" & $sUrl[0] & "|" & $sID)
                      $iRet = _BuildPopupsPPH($sID, $sDate, "PPH: " & $sTitle[0], $sUrl[0])
                      If $iRet Then $Show+=1
                  EndIf
              Next
              Sleep(30)
      ;~         If $Show > 0 Then ShowLatestJobs()
      ;~         _ArrayDisplay($aPPH)
              FileDelete($sTempFile)
              InetClose($hDownload)
              $hDownload = 0
              $hTimer = 0
              Return $Show
          EndIf
          Sleep(30)
      EndFunc   ;==>_CheckPPH
    • By malicioussoap
      back when I was still doing autohotkey you could write (in code) spanisha::á
      and whenever you were in google docs or notepad you could type (in the document) spanisha  and it instantly turns it into á 
      I tried doing this in autoit, here's what I have so far (my entire code so if this language requires a main function or a return/exit to function properly please let me know):
      ;is this a proper comment? HotKeySet ( "spanisha" , "SendAltered" ) Func SendAltered() Send("á", flag = 0); EndFunc I assume that autoit follows a sort of contemporary hotkey pressing model where you have to hold all keys at the same time? which makes this impossible. So
      I'm wondering if anyone has a workaround for this? or maybe an alternative to HotKeySet()
      I have a vague memory of someone saying that doing something like spanisha:á would work. I don't know if I'm slightly off syntax but this doesn't work.
      Also I tried doing 
      ;is this a proper comment? ;HotKeySet ( "a" , "SendAltered" ) ;spanisha::á Func SendAltered() Send("á"); EndFunc just to try and debug,
      I'm also wondering if my approach is fundamentally wrong since HotKeySet() was made for something like !^A. Or if Send() is syntactically wrong.
      I'm also noticing on these forums that specifying installation is important so to whom it may concern I downloaded both installers, editor and main files. Although I'm about to be real mad if the editor installation makes a difference.
    • By shelly
      I have to press tab to reach a selected button then double click on that
      Here's my script but its not working:
      WinActivate("Policy Decisions -- Webpage Dialog","")
      Sleep(3000)
      Send("{TAB}")
      Send("{TAB}")
      Send("{TAB}")                    // at this point its working according to my need  but double click is not working
      Mouseclick("Left",510, 320, 2, 0)

    • By TheDcoder
      See this thread for info:
    • By nooneclose
      Why can I not click on either of my input fields?
      #Region ### START Koda GUI section ### Form= Global $Form1 = GUICreate("Form1", 730, 437, 192, 124) ;GUISetFont(14, 800, 0, "MS Sans Serif") GUISetBkColor(0xC0DCC0) Global $Label1 = GUICtrlCreateLabel("Enter your Password. UserName is auto filled", 62, 40, 604, 41, $SS_CENTER) GUICtrlSetFont(-1, 26, 800, 0, "MS Sans Serif") Global $Label2 = GUICtrlCreateLabel("User Name:", 120, 130, 604, 31, $SS_LEFT) GUICtrlSetFont(-1, 20, 800, 0, "MS Sans Serif") Global $Label3 = GUICtrlCreateLabel("Password:", 135, 210, 604, 31, $SS_LEFT) GUICtrlSetFont(-1, 20, 800, 0, "MS Sans Serif") Global $Input1 = GUICtrlCreateInput(@UserName, 274, 130, 185, 32) GUICtrlSetFont(-1, 14, 800, 1, "MS Sans Serif") Global $Input2 = GUICtrlCreateInput("Password", 274, 210, 185, 32, $ES_PASSWORD) GUICtrlSetFont(-1, 14, 800, 0, "MS Sans Serif") Global $OK = GUICtrlCreateButton("OK", 274, 270, 185, 57) GUICtrlSetFont(-1, 20, 800, 0, "MS Sans Serif") GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $OK Global $UserName = GUICtrlRead($Input1) Global $PassWord = GUICtrlRead($Input2) ExitLoop EndSwitch WEnd ; Delete the GUI window GUIDelete()  
×
×
  • Create New...