2012-08-09 127 views
0

有兩個表SQL Server 2008中選擇問題

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

我一定要顯示多少個電郵每個用戶,按天進行分組,以便通過電子郵件總數發送的那一天。 我最好還是提供了一個例子:

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 

我試過,但顯然是行不通的。

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 
+0

我看到您的更新。這是因爲您在您的問題中陳述過,您希望結果「通過當天發送的全部電子郵件訂購」 – 2012-08-09 19:56:52

回答

1

這應該這樣做:

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 

現在,這個隱藏誰送沒有電子郵件的用戶(計數= 0)。如果要包括那些,你應該切換到這一點:

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 

更新

對於所需的順序,你應該去:

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 
+0

我只需要發送電子郵件的用戶。 SentAt是日期時間,我必須在白天進行查詢。 – gigi 2012-08-09 19:30:13

+0

因此使用解決方案#1 :) – 2012-08-09 19:30:36

+0

@Adrian - 解決方案#1如何忽略'SentAt'中的時間? – HABO 2012-08-09 19:42:07

0
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