mbigun
mbigun

Reputation: 1302

How to SELECT from several tables with additional conditions?

I have table "Table_Codes" in my SQL Server database

Code | Description | Owner | Location
A202   SomeDescr1    Owner1       M-3
B301   SomeDescr2    Owner2       M-3
C898   SomeDescr3    Owner3       M-2
B744   SomeDescr4    Owner4       M-3
V123   SomeDescr5    Owner5       M-3         - code is not define in second table

Also I have table "Table_Stock"

Code | Qty |     DC
A202    10       M-3
B301    12       M-2      !-not the same location like in 1st table for this code
C898    90       M-2
B744   120       M-3

I can't to build correct query to select next result from this tables:

    Code |    Qty(Location=DC) |  Qty on alternate DC (Location from 1st table <> DC)
    A202             10                       0
    B301              0                      12
    C898             90                       0
    B744            120                       0
    V123   Not in stock            Not in stock

I can do it by using auxiliary tables. But I want to know how to do it by using single SELECT query?

Upvotes: 0

Views: 63

Answers (1)

lc.
lc.

Reputation: 116488

Something like this (SQL Fiddle)?

SELECT c.Code,
    CASE WHEN s.Code IS NULL THEN 'Not in stock' 
        ELSE CAST(SUM(CASE WHEN s.DC = c.Location THEN s.Qty ELSE 0 END) AS VARCHAR(20)) END,
    CASE WHEN s.Code IS NULL THEN 'Not in stock' 
        ELSE CAST(SUM(CASE WHEN s.DC <> c.Location THEN s.Qty ELSE 0 END) AS VARCHAR(20)) END
FROM Table_Codes c
LEFT OUTER JOIN Table_Stock s ON c.Code = s.Code
GROUP BY c.Code, s.Code

Note the only way to do this in one query is to cast the second and third columns to a character type. Depending on what you want to do on the other end of the query, you might want to consider returning NULL instead of 'Not in stock'.

Upvotes: 2

Related Questions