Search code examples
sqlsql-servert-sqlsql-server-2014

MS SQL 2014 TSQL pulling 3 records


I am trying to pick the 3 rows that have the 3 unique GUID's below:

  SELECT 
    number                                  AS 'ID #', 
    line                                    AS 'Line #', 
    network                                 AS Network,
    FORMAT(SUM(totalCost), N'c', 'en-US')   AS Total 
  FROM 
    theLine 
  WHERE 
    theGuid = '32e1319d-8842-4b98-9a66-c1e694417528' 
  AND 
    theGuid = '61e819a8-a37a-4105-aab0-e34df31d992d' 
  AND
    theGuid = '6675811d-9a32-4b62-a003-87344af03d6b' 
  GROUP BY 
    number, line, network

However, when I run this query I get no records back. If I just do 1 WHERE clause then I get that record related to that GUID but any more renders no results.

But what I need it to do is the following:

------------------------------------
|ID #  |Line # |Network |Total     |
------------------------------------
|1     |1      |USASV   |$5,000.00 |
|2     |1      |FJESC   |$4,920.00 |
|3     |1      |RTDEW   |$598.00   |

So, what am I doing wrong?


Solution

  • You can't have 3 different values all in the same row. Either change your AND to OR or use the IN operator.

      SELECT 
        number                                  AS 'ID #', 
        line                                    AS 'Line #', 
        network                                 AS Network,
        FORMAT(SUM(totalCost), N'c', 'en-US')   AS Total 
      FROM 
        theLine 
      WHERE 
        theGuid = '32e1319d-8842-4b98-9a66-c1e694417528' 
      OR
        theGuid = '61e819a8-a37a-4105-aab0-e34df31d992d' 
      OR
        theGuid = '6675811d-9a32-4b62-a003-87344af03d6b' 
      GROUP BY 
        number, line, network
    

    Or:

      SELECT 
        number                                  AS 'ID #', 
        line                                    AS 'Line #', 
        network                                 AS Network,
        FORMAT(SUM(totalCost), N'c', 'en-US')   AS Total 
      FROM 
        theLine 
      WHERE 
        theGuid IN (
                    '32e1319d-8842-4b98-9a66-c1e694417528',
                    '61e819a8-a37a-4105-aab0-e34df31d992d',
                    '6675811d-9a32-4b62-a003-87344af03d6b' 
                   )
      GROUP BY 
        number, line, network