How to Query Data From SQL Server?

后端 未结 2 1742
野的像风
野的像风 2021-01-19 03:27

I have a problem in query data from database to make report in VB.NET. I use the Business Object to do the report. And here is my example data:

_____________         


        
2条回答
  •  迷失自我
    2021-01-19 04:12

    If I understood you correctly, this should do what you want:

    SELECT  A.Id, 
            A.Item, 
            A.Unit, 
            CASE WHEN B.Id IS NOT NULL THEN 'Undefined' ELSE [Unit Price] END [Unit Price],
            A.Quantity,
            A.Amount
    FROM (  SELECT  Id, Item, Unit,
                    CAST(MIN([Unit Price]) AS VARCHAR(20)) [Unit Price], 
                    SUM(Quantity) Quantity, SUM(Amount) Amount
            FROM YourTable
            GROUP BY Id, Item, Unit) A
    LEFT JOIN ( SELECT Id
                FROM YourTable
                GROUP BY Id
                HAVING COUNT(DISTINCT [Unit Price]) > 1) B
        ON A.Id = B.Id
    

    Added an sql fiddle for you to try. (Credit to @bonCodigo, since I based my fiddle on the one he already had, but with my code).

    This is the result:

    ID  ITEM        UNIT        PRICE       QUANTITY    AMOUNT
    1   Gasoline    L           Undefined   90          539.9
    2   Water       Bottle      5.00        20          99.9
    3   Meat        Kg          14.90       15          223.5
    4   Milk        Can         7.45        30          223.5
    

提交回复
热议问题