使用group by显示是否为特定ID上传了图片

时间:2015-09-03 21:54:30

标签: sql-server

架构:

function countTime(duration) {
     var expected = 1;
     var secsLeft;
     var inter;
     var startT = new Date().getTime();

     inter = setInterval(function() {
         //change in seconds
         var sChange = Math.floor((new Date().getTime() - startT) / 1000);

         if (sChange === expected) {
             expected++;
             secsLeft = duration - sChange;
             console.log("seconds Left" + secsLeft);
         }

         if (secsLeft === 0) {
             window.clearInterval(inter);
             console.log("cleared");
         }
     }, 100);
 }
 countTime(60);

查询:

tablename : Picture_profile
personID, pictureNumber(count which increase upon adding a picture for an id there can be many pictures),pictureName, datePictureAdded

tablename : person
personID, phone, address, zip, city, email,country and many other columns

上面的查询工作正常并显示我想要的但问题是

如果我需要显示所有列。我应该做什么" group by" 对于select中的所有列。

有没有办法可以消除这个群体?

1 个答案:

答案 0 :(得分:0)

这仅适用于相当新版本的Sql Server,但我使用APPLY运算符:

SELECT p.*,
    COALESCE(a.HasPicture, 'N') PictureIsUploaded
FROM person_profile p
OUTER APPLY 
(
    SELECT TOP 1 'Y' HasPicture 
    FROM Picture_profile pic
    WHERE pic.personID = p.personID
) a

您也可以将此作为相关派生表(子查询):

SELECT p.*,
    COALESCE(
        (SELECT TOP 1 'Y' 
         FROM Picture_profile pic
         WHERE pic.personID = p.personID)
    , 'N') PictureIsUploaded
FROM person_profile p

当您需要来自所选Picture_Profile记录的多个值时,APPLY运算符优于相关子查询的优势。例如,这样您就可以在结果中包含picturenamepicturenumber字段,但只会产生一次子查询费用。