我在我的项目中使用以下查询,但问题重复值正在重复。我也使用了DISTINCT和GROUP BY。请帮帮我。
查询:
SELECT
dob.user_info.users_id AS user_id,
CONVERT(
nvarchar(50),
dbo.chat_message.time
) AS chat_time,
dbo.user_info.users_name AS user_name
FROM
dbo.user_info
INNER JOIN
dbo.chat_message ON dbo.user_info.eve_id = 19
AND dbo.user_info.user_id = dbo.chat_message.user_id
AND dbo.user_info.user_id <> 478
AND dbo.user_info.user_type <> 'admin'
AND dbo.chat_message.delete_status = 1
GROUP BY
dbo.user_info.user_id,
dbo.user_info.user_name,
time
OUTPUT应该像
|505, mothan, Chk, 2015-03-23 10:24:15.000|
|551,yasar, hi yasar how are you ?, 2015-03-16 16:41:49.000|
|566, Jegan , hi jegan, 2015-03-16 16:41:07.000|
|567 , Prabu, hi prabu, 2015-03-16 16:41:07.000|
如果服务器日期等于聊天日期,那么它应该只显示聊天时间。如果服务器日期大于聊天日期,那么它应该显示日期,如24feb。
答案 0 :(得分:1)
更新版本:
with cte as
(
SELECT dob.user_info.users_id AS user_id,
CONVERT(nvarchar(50), dbo.chat_message.time) AS chat_time,
dbo.user_info.users_name AS user_name,
dbo.chat_message.message
FROM
dbo.user_info
INNER JOIN
dbo.chat_message ON dbo.user_info.eve_id = 19
AND dbo.user_info.user_id = dbo.chat_message.user_id
AND dbo.user_info.user_id <> 478
AND dbo.user_info.user_type <> 'admin'
AND dbo.chat_message.delete_status = 1
)
select * from cte t1
where not exists (select 1 from cte t2
where t2.chat_time > t1.chat_time
and t2.user_id = t1.user_id)
答案 1 :(得分:0)
您有不同的时间字段,因此可以获得多个结果。 如果您将时间字段排除在组外并使用最大值(时间),您将获得结果中的最新时间。
SELECT dob.user_info.users_id AS user_id,
CONVERT(nvarchar(50), MAX(dbo.chat_message.time)) AS chat_time,
dbo.user_info.users_name AS user_name, dbo.chat_message.message FROM dbo.user_info INNER JOIN dbo.chat_message ON dbo.user_info.eve_id = 19 AND dbo.user_info.user_id = dbo.chat_message.user_id AND dbo.user_info.user_id <> 478 AND dbo.user_info.user_type <> 'admin' AND dbo.chat_message.delete_status = 1
GROUP BY dbo.user_info.user_id, dbo.user_info.user_name, dbo.chat_message.message
答案 2 :(得分:0)
非常好的问题,如果有效的话,请你试试下面的一个
SELECT
Distinct dob.user_info.users_id AS user_id,
CONVERT(
nvarchar(50),
dbo.chat_message.time
) AS chat_time,
dbo.user_info.users_name AS user_name
FROM
dbo.user_info
INNER JOIN
dbo.chat_message ON dbo.user_info.eve_id = 19
AND dbo.user_info.user_id = dbo.chat_message.user_id
AND dbo.user_info.user_id <> 478
AND dbo.user_info.user_type <> 'admin'
AND dbo.chat_message.delete_status = 1
GROUP BY
dbo.user_info.user_id