2010-12-07 48 views
0

我只是想一些一般性的建议。我的表结构像这样(或者说,我一直在考虑的表为工作):更多的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”的物料计数'都是平等的,所有交付物品都已交付。有任何想法吗?我已经加入周围玩弄,但我很困惑:(

感谢

+0

@Abe苛刻但公平! – 2010-12-07 21:17:36

回答

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

您可以用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 
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 
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