简体   繁体   中英

sql server 2008 select issue

There are two tables

Users:Id(PK int), Username(varchar (50))
Emails:Id(PK int), UserId(FK int), Subject(varchar(50)), Content(varchar(250)), SentAt(datetime)

I have to display how many emails each user sent , grouped by day, order by total emails sent that day. I'd better provide an example:

Date     |User       |Total
---------|-----------|-------
2012-4-5 |username1  |7
2012-4-5 |username2  |2
2012-4-2 |username1  |3
2012-3-24|username1  |12
2012-3-24|username5  |2

I tried this but obviously it is not working.

ALTER PROCEDURE spGetStatistics
AS
SELECT e.SentAt, u.Username, ( SELECT COUNT(*) FROM Emails e2 WHERE e2.SentAt=e.SentAt AND e2.UserID=u.UserID ) AS Total
FROM Emails e INNER JOIN Users u ON e.UserID=u.UserID
GROUP BY e.SentAt
ORDER BY Total

LE:

Using the solution provided by Adrian which is:

    SELECT CAST (e.SentAt AS date), u.Username,  COUNT(*) AS Total
    FROM Emails e INNER JOIN Users u ON e.UserID=u.UserID
    GROUP BY CAST (e.SentAt AS date), u.Username
    ORDER BY Total

I got this:
    Date       |User       |Total
    -----------|-----------|-------
    2012-09-08 |username1  |1
    2012-09-07 |username2  |2
    2012-09-08 |username2  |2

instead of

    Date       |User       |Total
    -----------|-----------|-------
    2012-09-08 |username2  |2
    2012-09-08 |username1  |1
    2012-09-07 |username2  |2


It seems to be working like this:
SELECT CAST (e.SentAt AS date), u.Username,  COUNT(*) AS Total
FROM Emails e INNER JOIN Users u ON e.UserID=u.UserID
GROUP BY CAST (e.SentAt AS date), u.Username
ORDER BY CAST (e.SentAt AS date) DESC, Total DESC

This should do:

SELECT 
    cast(e.SentAt as Date) [Date], 
    u.Username,
    COUNT(*) AS Total
FROM Emails e INNER JOIN Users u ON e.UserID=u.UserID
GROUP BY cast(e.SentAt as Date), u.Username
ORDER BY 3

Now, this hides the users who sent no emails (count=0). If you want to include those, you should switch to this:

SELECT 
    cast(e.SentAt as Date) [Date], 
    u.Username,
    COUNT(e.Id) AS Total
FROM Users u LEFT JOIN Emails e ON e.UserID=u.UserID
GROUP BY cast(e.SentAt as Date), u.Username
ORDER BY 3

Update

For the desired order, you should go with:

SELECT 
    cast(e.SentAt as Date) [Date], 
    u.Username,
    COUNT(*) AS Total
FROM Emails e INNER JOIN Users u ON e.UserID=u.UserID
GROUP BY cast(e.SentAt as Date), u.Username
ORDER BY cast(e.SentAt as Date), Total DESC
SELECT e.SentAt, u.Username, count(e.Id) AS Total
FROM Emails e
  INNER JOIN Users u ON (e.UserID = u.UserID)
GROUP BY e.SentAt, u.Username
ORDER BY Total

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