更多SQL头痛

时间:2010-12-07 21:07:25

标签: c# asp.net sql

我只是喜欢一些一般的建议。我的表格结构如此(或者更确切地说,我已经给过的表格):

> Deliveries 
 ID (Primary Key) 
 customer
...(irrelevant fields)...


> DeliveryItems
ID (primary key)
deliveryid (links to ID of deliveries)
delivered (integer - 2 means delivered, 1 not delivered yet)
...(irrelevant fields)...

无论如何,在我创建的SQL查询中,我需要执行以下操作:

用户访问该页面,该页面是“交付的客户参数”,因此它显示链接到该客户的所有交货。然后,我需要一个动态生成的列来显示我的所有物品是否已经交付 - 所以基本上,如果该货物的物品数量等于该物品的物品数量为2的物品'相同,交付的所有物品都已送达。有任何想法吗?我玩弄了很多连接,但我很困惑:(

由于

4 个答案:

答案 0 :(得分:3)

select d.*,
    case when di.TotalCount = DeliveredCount then 1 else 0 end as DeliveryComplete
from Deliveries d
inner join (
    select deliveryID, 
        count(*) TotalCount, 
        count(case when delivered = 2 then 1 end) as DeliveredCount
    from DeliveryItems 
    group by deliveryID
) di on d.ID = di.deliveryID

答案 1 :(得分:1)

您可以从case / when / then获得一些帮助:

select d.*, 
case 
   when exists (select * from DeliveryItems di 
                where di.deliveryid = d.id 
                and di.delivered <> 2)
   then 0
   else 1 
end as DeliveryComplete
from Deliveries d
where d.customer = @customerId

答案 2 :(得分:0)

案例陈述:

SELECT 
    DeliveryId, 
    CASE 
        WHEN SUM(Delivered) = 2 * COUNT(Id) THEN 'All items delivered'
        ELSE 'Not Delivered'
    END AS [Status]
FROM 
    DeliveryItems
GROUP BY 
    DeliveryId

答案 3 :(得分:0)

试试这个。

SELECT b.*
    , CASE WHEN a.min_delivered = 1 THEN 'Get back to work'
           ELSE 'All done!'
           END AS [Are they all done]
FROM
(
    SELECT customer
        , MIN(delivered) AS min_delivered
    FROM Deliveries a
    JOIN DeliveryItems b
        ON a.id = b.deliveryid
    WHERE a.customer = @customer
    GROUP BY customer
) a
JOIN Deliveries b
    ON a.customer = b.customer