我编写了一个SQL查询,每月为列ipAdress
和ID
创建前10名。结果是正确的但我需要另一种格式的结果。
你能帮助我找到正确的格式吗?
我的SQL查询是
SELECT
MyMonth,
ipAddress,
ID ,
Records
FROM
(
SELECT
MyMonth ,
ipAddress,
ID,
Records,
ROW_NUMBER() OVER(PARTITION BY MyMonth ORDER BY so.Records DESC) AS RowNum
FROM
(
SELECT
LEFT(DATENAME(month,startDate),3) + ' ''' + RIGHT(YEAR(startDate),2) AS MyMonth
,ipAddress, ID ,COUNT(1) AS Records
FROM
[TEST_AUSWERTUNG].[dbo].[Evaluation]
GROUP BY
LEFT(DATENAME(month,startDate),3) + ' ''' + RIGHT(YEAR(startDate),2) ,ipAddress, ID
)so
)x
WHERE x.RowNum < 11
结果是例如
Aug'14 145.998.111.115 14 191481
Aug '14 145.998.991.145 E1 81448
Aug '14 11.14.48.11 P4 44544
Aug '14 145.998.49.149 U4 95814
Aug '14 11.4.949.49 CD 94941
Aug '14 11.4.949.45 XT 99449
Aug '14 11.4.949.45 CD 91188
Aug '14 145.998.49.54 XT 91994
Aug '14 11.4.949.49 XT 91954
Aug '14 145.998.49.44 BM 91444
Jun '14 145.998.111.115 14 118494
Jun '14 145.998.991.145 E1 49915
Jun '14 11.14.48.11 P4 41114
Jun '14 145.998.49.159 XB 49414
Jun '14 145.998.49.149 U4 94449
Jun '14 145.998.49.199 XB 94148
Jun '14 11.4.949.49 CD 99154
Jun '14 11.4.949.45 XT 99154
Jun '14 145.998.49.44 XT 91449
Jun '14 145.998.49.54 XT 91554
但我需要这样:
Aug'14 145.998.111.115 14 191481 Jun '14 145.998.111.115 14 118494
Aug '14 145.998.991.145 E1 81448 Jun '14 145.998.991.145 E1 49915
Aug '14 11.14.48.11 P4 44544 Jun '14 11.14.48.11 P4 41114
Aug '14 145.998.49.149 U4 95814 Jun '14 145.998.49.159 XB 49414
Aug '14 11.4.949.49 CD 94941 Jun '14 145.998.49.149 U4 94449
Aug '14 11.4.949.45 XT 99449 Jun '14 145.998.49.199 XB 94148
Aug '14 11.4.949.45 CD 91188 Jun '14 11.4.949.49 CD 99154
Aug '14 145.998.49.54 XT 91994 Jun '14 11.4.949.49 CD 99154
Aug '14 11.4.949.49 XT 91954 Jun '14 11.4.949.45 XT 99154
Aug '14 145.998.49.44 BM 91444 Jun '14 145.998.49.44 XT 91449
任何人都有解决方案吗?
答案 0 :(得分:1)
您没有解释您希望通过查询实现的目标,我不打算对其进行调查。即便如此,我会告诉你如何做到这一点:
ipAddress
和ID
像这样(伪代码):
WITH T ( list of fields in your query )
AS
( your query )
SELECT
T1.MyMonth, T1.ipAddress, T1.ID, T1.records,
T2.MyMonth, T2.ipAddress, T2.ID, T2.records
FROM
(T WHERE MyMonth='Aug ''14') T1
INNER JOIN
(T WHERE MyMonth='Jun ''14') T2
ON T1.ipAddress = T2.ipAddress and T1.ID = T2.ID
我确信你必须知道你想要实现的目标,并且能够以某种方式改进查询,一旦你有了它。