我正在尝试选择下面有3个唯一GUID的3行:
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
然而,当我运行此查询时,我没有得到任何记录。如果我只是执行 1 WHERE子句,那么我会获得与该GUID相关的记录,但不再呈现任何结果。
但我需要它做的是:
------------------------------------
|ID # |Line # |Network |Total |
------------------------------------
|1 |1 |USASV |$5,000.00 |
|2 |1 |FJESC |$4,920.00 |
|3 |1 |RTDEW |$598.00 |
那么,我做错了什么?
答案 0 :(得分:5)
您不能在同一行中拥有3个不同的值。将AND
更改为OR
或使用IN
运算符。
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
或者:
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
答案 1 :(得分:1)
在WHERE子句中使用OR而不是AND
答案 2 :(得分:1)
这是IN
的一个很好的示例用例,但我不确定为什么你有GROUP BY
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