有没有办法让我在连接表上执行COUNT而不必使用GROUP BY语句? 我必须将此SQL插入到遗留应用程序中,该应用程序正在解析此结果但无法处理GROUP BY部分。
这就是我现在拥有的(在sql-server中工作,但在其他应用程序中没有):
SELECT TOP 10 au.pref_language,au.username,am.IsOpenIdAccount,am.facebookid,au.sex,au.firstname,au.middlename,au.lastname,am.email,
c.id AS objectid,c.title AS objecttitle,c.friendlyurl as objecturl,c.objecttype,am.CreateDate,c.description_nl,c.description_en,
COUNT(distinct ap.id) as totalphotos,
COUNT(distinct ar.id) as totalreviews,
COUNT(distinct fm.id) as totalfreemedia
FROM locations c
INNER JOIN aspnet_users au on au.UserId=c.userid
INNER JOIN aspnet_membership am ON am.userid=au.userid
LEFT JOIN location_photos ap on ap.objectid=c.id
LEFT JOIN location_reviews ar on ar.objectid=c.id
LEFT JOIN freemedia fm on fm.objectid=c.id AND fm.objecttype=c.objecttype
WHERE c.title<>''
GROUP BY au.pref_language,au.username,am.IsOpenIdAccount,am.facebookid,au.sex,au.firstname,au.middlename,au.lastname,am.email,
c.id ,c.title ,c.friendlyurl ,c.objecttype,am.CreateDate,c.description_nl,c.description_en
我需要这样的事情:
SELECT TOP 10 au.pref_language,au.username,am.IsOpenIdAccount,am.facebookid,au.sex,au.firstname,au.middlename,au.lastname,am.email,
c.id AS objectid,c.title AS objecttitle,c.friendlyurl as objecturl,c.objecttype,am.CreateDate,c.description_nl,c.description_en,
COUNT(distinct ap.id) as totalphotos,
COUNT(distinct ar.id) as totalreviews,
COUNT(distinct fm.id) as totalfreemedia
FROM locations c
INNER JOIN aspnet_users au on au.UserId=c.userid
INNER JOIN aspnet_membership am ON am.userid=au.userid
LEFT JOIN location_photos ap on ap.objectid=c.id
LEFT JOIN location_reviews ar on ar.objectid=c.id
LEFT JOIN freemedia fm on fm.objectid=c.id AND fm.objecttype=c.objecttype
WHERE c.title<>''
答案 0 :(得分:2)
你可以在Sql中使用一个视图,然后运行一个Select吗?
CREATE VIEW [dbo].[vwMyView]
AS
SELECT TOP 10 au.pref_language,au.username,am.IsOpenIdAccount,am.facebookid,au.sex,au.firstname,au.middlename,au.lastname,am.email,
c.id AS objectid,c.title AS objecttitle,c.friendlyurl as objecturl,c.objecttype,am.CreateDate,c.description_nl,c.description_en,
COUNT(distinct ap.id) as totalphotos,
COUNT(distinct ar.id) as totalreviews,
COUNT(distinct fm.id) as totalfreemedia
FROM locations c
INNER JOIN aspnet_users au on au.UserId=c.userid
INNER JOIN aspnet_membership am ON am.userid=au.userid
LEFT JOIN location_photos ap on ap.objectid=c.id
LEFT JOIN location_reviews ar on ar.objectid=c.id
LEFT JOIN freemedia fm on fm.objectid=c.id AND fm.objecttype=c.objecttype
WHERE c.title<>''
GROUP BY au.pref_language,au.username,am.IsOpenIdAccount,am.facebookid,au.sex,au.firstname,au.middlename,au.lastname,am.email,
c.id ,c.title ,c.friendlyurl ,c.objecttype,am.CreateDate,c.description_nl,c.description_en
GO
然后从你的App解析只需输入:
SELECT
pref_language,
username,
IsOpenIdAccount,
facebookid,
sex,
firstname,
middlename,
lastname,
email,
objectid,
objecttitle,
objecturl,
objecttype,
CreateDate,
description_nl,
description_en,
totalPhotos,
totalReviews,
totalFreeMedia
from [dbo].vwMyView