我几天前就开始学习SQL了,我接下来的查询在“案例”附近给出了一个错误,我似乎无法弄明白:
SELECT * , Stuff((SELECT ', ' + CAST( orderid as varchar(10))
FROM( oitems t2
case when (ocardtype in ('PayPal','Sofort') OR
ocardtype in ('mastercard','visa') and
odate is not null) then
FOR XML PATH(''), 1, 2, '') [Proccessed] else FOR XML PATH(''), 1, 2, '') [NotProccessed] end)
FROM orders t1
Group by orderid,t1.odate, t1.ocardtype
我想你得到了这段代码应该做的,但我不确定这是否是使用select case
的正确方法。
oitems table
+---------+-----------+----------+
| orderid | catalogid | numitems |
+---------+-----------+----------+
| o737 | 353 | 1 |
| o738 | 364 | 4 |
| o739 | 353 | 3 |
| o740 | 364 | 6 |
| o741 | 882 | 2 |
| o742 | 224 | 5 |
| o743 | 224 | 2 |
+---------+-----------+----------+
orders table
+-----------------+------------+------------+
| orderid | ocardtype | odate |
+-----------------+------------+------------+
| o737 | Paypal | | 'OK
| o738 | MasterCard | 01.02.2012 | 'OK
| o739 | MasterCard | 02.02.2012 | 'OK
| o740 | Visa | 03.02.2012 | 'OK
| o741 | Sofort | | 'OK
| o742 | | | 'ignore because ocardtype is empty
| o743 | MasterCard | | 'ignore because Mastercard no odate
+-----------------+------------+------------+
预期结果
+-----------+------------------------+--------------+
| catalogid | ProcessedSucssessfully | NotProcessed |
+-----------+------------------------+--------------+
| 353 |o737,o739 | |
| 364 |o738,o740 | |
| 882 |o741 | |
| 224 | |o742,o743 |
+-----------+------------------------+--------------+
我有以下条件,您可以在上述代码的案例陈述中找到
如果ocardtype
为空,则将orderid
添加到NotProcessed
如果某个订单的ocardtype
为万事达卡或维萨而且odate为空,则将orderid添加到NotProcessed
如果ocardtype
是Paypal或Sofort,则不要检查odate并将orderid
添加到ProcessedSucssessfully
答案 0 :(得分:2)
检查此请求
SELECT CatalogId, ProcessedSucssessfully =
STUFF((SELECT ', ' + b.OrderId
FROM oitmes b JOIN orders o ON b.OrderId = o.OrderId
WHERE b.CatalogId = a.CatalogId
AND (o.OcardtType in ('PayPal','Sofort') OR o.OcardtType in ('mastercard','visa') and o.odate is not null)
FOR XML PATH('')), 1, 2, ''),
NotProcessed =
STUFF((SELECT ', ' + c.OrderId
FROM oitmes c JOIN orders o ON c.OrderId = o.OrderId
WHERE c.CatalogId = a.CatalogId
AND (o.OcardtType in ('mastercard') OR o.OcardtType is null) and o.odate is null
FOR XML PATH('')), 1, 2, '')
FROM oitmes a
GROUP BY a.CatalogId
SQLFiddle上的演示
答案 1 :(得分:0)
您似乎在FROM
之前使用CASE
子句而不是之后:
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber
我能想到的其他事情是你没有使用CASE
返回true或false,这可能会让你犯错误。