从数据库中获取数据并在DataGridView中显示

时间:2012-08-26 11:23:13

标签: c# sql-server datagridview

我正在使用此查询从SQL Server 2008中获取数据:

select 
    g.godown_name, s.supplier_name, t.type_name,
    r.bags_instock, b.lb_per_bag, t.rate
from 
    tbl_godown g, tbl_yarn_supplier s, tbl_yarn_type t,
    tbl_yarn_receive r, tbl_godown_transaction gt, tbl_yarn_book b
where 
    r.book_id = b.book_id and
    s.supplier_id = b.supplier_id and
    t.type_id = b.type_id and
    gt.godown_id = g.godown_id and
    gt.receive_id = r.receive_id

结果是:

enter image description here

此处某些交易具有相同的GodownSuppliarTpe& lbs_per_bag

1. 1 & 7
2. 2,3,4,5
3. 8,9,10,11
4. 12
5. 6

如果任何行具有相同的Godown, Suppliar, Tpe & lbs_per_bag,则不应重复

结果应该是这样的。

感谢

等待回复

enter image description here

2 个答案:

答案 0 :(得分:2)

我就是这样做的:

SELECT 
    g.godown_name, 
    s.supplier_name, 
    t.type_name,
    b.lb_per_bag, 
    SUM(r.bags_instock) As total_bags_instock, 
    SUM(t.rate * r.bags_instock) 
        /SUM(r.bags_instock) As average_rate

FROM tbl_godown_transaction  As gt
JOIN tbl_godown          As g  ON gt.godown_id   = g.godown_id 
JOIN tbl_yarn_receive    As r  ON gt.receive_id  = r.receive_id
JOIN tbl_yarn_book       As b  ON r.book_id      = b.book_id 
JOIN tbl_yarn_supplier   As s  ON s.supplier_id  = b.supplier_id 
JOIN tbl_yarn_type       As t  ON t.type_id      = b.type_id

GROUP BY
    g.godown_name, 
    s.supplier_name, 
    t.type_name,
    r.lb_per_bag

答案 1 :(得分:1)

更喜欢使用内连接

 select 
        g.godown_name, s.supplier_name, t.type_name,
        r.bags_instock, b.lb_per_bag, t.rate
    from 
        tbl_godown g
        inner join tbl_godown_transaction gt
           on gt. gt.godown_id = g.godown_id 
        inner join  tbl_yarn_receive r
           on gt.receive_id = r.receive_id
        inner join tbl_yarn_book b
           on r.book_id = b.book_id
        inner join tbl_yarn_supplier s
           on  s.supplier_id = b.supplier_id
        inner join tbl_yarn_type t
           on t.type_id = b.type_id       
    group by    g.godown_name, s.supplier_name, t.type_name,
        r.bags_instock, b.lb_per_bag, t.rate