Sql server 具有group by和/或distinct和pivot的复杂SQL Server查询
我有一个具有以下结构的表(Sql server 具有group by和/或distinct和pivot的复杂SQL Server查询,sql-server,group-by,pivot,Sql Server,Group By,Pivot,我有一个具有以下结构的表(UserAction): UserActionPK - unique primary key of the UserAction table AgencyCode - unique name for an agency EditedKEY - key of a table edited by the user UserName - name of the user that edited the record EditedDate - day on which the
UserAction
):
UserActionPK - unique primary key of the UserAction table
AgencyCode - unique name for an agency
EditedKEY - key of a table edited by the user
UserName - name of the user that edited the record
EditedDate - day on which the edit was made
我需要查询这些数据,并最终得到一个数据透视集,其中一列用于代理代码,一组用户中的每一个都有一列(比如[JohnDoe]、[JoeSmith]、[SomeGuy])。在每个用户的列中,它将列出用户执行的用户操作总数。前/
AgencyCode JohnDoe JoeSmith SomeGuy
ABC 1 3 4
DEF 0 7 2
然而,有一种特殊情况。如果用户在一天内(EditeDate)对同一个精确记录(EditedKEY)执行了多个操作,则它应仅计为一个操作。例如,如果JohnDoe在2013年1月1日编辑了一条EditedKEY为“XXX”的记录1次,然后在2013年1月2日编辑了同一条EditedKEY为“XXX”的记录3次,则这些编辑应仅计入总数中的2次编辑。我基本上只需要在旋转EditeDate值之前将其分组。注意,EditedKEY值是一个guid,因此即使在机构之间,它也始终是唯一的
我有一个查询,它将获取我需要的数据并对其进行透视,但不使用相同的EditeDate、UserName和AgencyCode对UserActions进行分组:
select * from
(
select UserActionKEY, AgencyCode, EditedDate, UserName
from UserAction
where EditedDate >= @FromDate
and EditedDate <= @ToDate
) Pivot1
pivot
(
count(UserActionKEY)
for UserName in
(
[JohnDoe],
[JohnSmith],
[SomeGuy],
)
) Pivot2
在本例中,JohnDoe列应该有机构“ABC”的4个操作计数,即使他有该机构的5个记录,因为他当天有2个相同的“EditedKEY”(521A63CD-AEEF-44BF-BDCB-EE96373AC39A)操作,该操作仅计为1个操作 这种透视通常最好使用客户端应用程序代码,而不是SQL。SQL代码需要在前端知道查询开始时结果列的数量和名称。而不是直接的
计数(…)
,您需要在分组条件上执行SELECT DISTINCT加上一个附加字段Value=1
。然后执行一个SUM(Value)
来代替您的计数(…)
您能从表中发布一些数据吗?
UserActionPK AgencyCode EditedKEY UserName EditedDate
0F573329-0C83-44B8-AD9A-808D8795FCCF ABC 521A63CD-AEEF-44BF-BDCB-EE96373AC39A JohnDoe 3/11/2013
36321DB6-DA1B-430E-B85C-36372088860E ABC 521A63CD-AEEF-44BF-BDCB-EE96373AC39A JohnDoe 3/11/2013
BDC9B165-CC93-409A-BEAE-3365709F6E54 ABC 042D633F-47AC-4A5C-BE3B-B179E01AD5C9 JohnDoe 3/11/2013
2475344C-80DD-4898-A7CD-B41B2593F0FE DEF F6016422-BB24-4B39-A735-BCD1206AEA4A JohnDoe 3/11/2013
3CD7B9BB-428A-45E9-B254-8A2FD502B9F7 DEF C9A028F6-6E1A-4FD6-A549-D932BC20AA88 JohnDoe 3/11/2013
B0348158-1455-42DF-81EB-29704F08E920 ABC 6937C16A-752A-4D69-BBE9-932015B8C137 JohnDoe 3/12/2013
F1C5950D-05D2-48B6-BFC3-1C32FD970F76 ABC 521A63CD-AEEF-44BF-BDCB-EE96373AC39A JohnDoe 3/12/2013
502F67A2-6448-48FB-8BFE-74D21592BA48 ABC B3371961-06EE-4CD3-9373-87102EB793FA JoeSmith 3/11/2013
E797DFE0-8693-44FC-821F-46B745B37533 ABC 79E1F21F-C7D3-4F8C-8D51-536C34FF84D4 JoeSmith 3/11/2013