简体   繁体   中英

How to Use COUNT(*), but break down by repeating values in another Column

I have a table in SQL that is formatted like so:

ReportLogID | SiteID | ReportName | ReportPath   | UserName | RunDateTime 
------------|--------|------------|--------------|----------|------------
1           | 3      | Report 1   | C:\1.report  |User      | 2014-11-26
2           | 8      | Report 1   | C:\1.report  |User      | 2014-12-20
3           | 3      | Report 2   | C:\2.report  |User      | 2014-12-21
4           | 3      | Report 1   | C:\1.report  |User      | 2014-12-22

I have the following code to count the number of times a report has been run total, along with the last date it was run:

SELECT ReportName, MAX(RunDateTime) AS LASTRAN, COUNT(*) AS TIMESRAN FROM ReportLog GROUP BY ReportName ORDER BY TIMESRAN DESC 

I'm needing to run this report taking the SiteID into consideration. I know the report has been run a total of X times, and the last date it was run. However, I need to break it down by SiteID - so Report 1 was run a total of X times for SiteID 3, and last ran on YYYY-MM-DD. I've run into a roadblock.

Any assistance would be appreciated!

You can do it as following:

SELECT ReportName
  , MAX(RunDateTime) AS LASTRAN
  , COUNT(*) AS TIMESRAN
FROM ReportLog
GROUP BY ReportName
  , SiteID
ORDER BY TIMESRAN DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM