我正在尝试找出用户更改最多的值。 我有一个这样的用户表:
这是一个用户表,其中的条目未更改。如果用户更改了某些内容,则会创建一条新记录来跟踪用户的更改。
现在我想得到这样的东西:
我希望将列名(电子邮件,电话等)作为值,以便我进行排序。
有人知道我该怎么做吗?
编辑:我正在使用SSMS和T-SQL
答案 0 :(得分:0)
它看起来很恐怖,但是可以起作用:
select * into #q1 from (SELECT Row_number()OVER(ORDER BY i.CreationDate) rn, i.Email, i.Phone, i.Address, i.Phone, i.NumberOfKids
FROM user i) as t
SELECT Sum(CASE WHEN a.Email= b.Email THEN 0 ELSE 1 END) as Amount, 'Email' as ColumnName
FROM #q1 a
JOIN #q1 b
ON a.UserID= b.UserID
UNION ALL
SELECT Sum(CASE WHEN a.Address= b.Address THEN 0 ELSE 1 END) as Amount, 'Address' as ColumnName
FROM #q1 a
JOIN #q1 b
ON a.UserID= b.UserID
UNION ALL
SELECT Sum(CASE WHEN a.Phone= b.Phone THEN 0 ELSE 1 END) as Amount, 'Phone' as ColumnName
FROM #q1 a
JOIN #q1 b
ON a.UserID= b.UserID
UNION ALL
SELECT Sum(CASE WHEN a.NumberOfKids= b.NumberOfKids THEN 0 ELSE 1 END) as Amount, 'NumberOfKids' as ColumnName
FROM #q1 a
JOIN #q1 b
ON a.UserID= b.UserID
order by Amount desc
drop table #q1