Please show me how to write a unique sql statement - sql

Below are the tables I need to pull data from - I only included columns to be used here in this example:
Maintable:
mainkey, account
-----------------
1, 100
2, 200
3, 300
Childtable:
linkedkeytomain, type, color
---------------------------
2, b, blue
2, y, yellow
2, r, red
2, g, green
2, w, white
My goal is to be able to write a select that will only show one line of data Where Type = 'b' and Type = 'w' and Type = 'r' only:
For instance,
Account, c1, c2, c3
---------------------
200, blue, white, red
Can someone please show me how to obtain this complex select. Many thanks in advance.
blumonde

Your problem is that you need to pivot the groups. Here is a simple way:
select account,
max(case when seqnum = 1 then color end) as color1,
max(case when seqnum = 2 then color end) as color2,
max(case when seqnum = 3 then color end) as color3
from (select account, color,
row_number() over (partition by account order by color) as seqnum
from maintable mt join
childtable ct
on ct.linkedkeytomain = mt.mainkey
) t
group by account

Related

SQL to pivot a field with CASE WHEN

My table has fields: Item, AttributeNo_, AttrbuteValue. Each AttributeNo_ has a matched AttributeName.
e.g.
Item, AttributeNo_, AttributeValue
A, 1, Yellow
A, 2, Round
……
(AttributeNo_ 1 means color, 2 means shape as AttributeName)
This is what I'm trying to achieve:
Item, Color, Shape
A, Yellow, Round
……
My code is:
select Item,
case when AttributeNo_=1 then AttributeValue end AS Color,
case when AttributeNo_=2 then AttributeValue end AS Shape
from table;
The result is like:
Item, Color, Shape
A, Yellow, Null
A, Null, Round
……
How can I achieve the correct result?
Thanks in advance!
Use aggregation:
select Item,
max(case when AttributeNo_ = 1 then AttributeValue end) AS Color,
max(case when AttributeNo_ = 2 then AttributeValue end) AS Shape
from table
group by Item;

SQL match if not 0 or > 4

Here is my issue.
I have 4 tables as example (Shape -> ShapeDetails -> ShapeSize -> ShapeColor)
Basically each time I create a new Shape there is new line ShapeColor created( and for each colors I selected is created new line in the table ShapeColor) Inconvenient I know but the software I have to use has been designed like this.
So , a Shape can have a lot of colors but I would like to match based on the "name" of the color those which have color "red", "pink","blue" BUT if one of them have "red","pink","blue" and "yellow" in this case this one should not be matched.
I would like to match those between 1 and/or 3 colors.
Example (Colors: red,pink,blue,yellow) :
0 0 0 0 (none of these colors = NOK) not in the resulstSet
1 0 0 0 (only red but not pink blue yellow = OK) Match in the resultSet
0 1 0 0 (only pink but not red blue yellow = OK) Match
1 1 0 0 (only red pink but not blue and yellow = OK) Match
1 0 1 0 ...
1 1 1 1 (all of these colors = NOK) not in the resultsSet
btw, I use some joins to get to ShapeColor
I don't know how can I solve this problem with one SQL query, any kind of help will be very appreciated
SELECT s.id
FROM shape s INNER JOIN shape_color sc ON s.id=sc.id
GROUP BY s.id
HAVING
SUM(CASE WHEN sc.color='red' OR sc.color='pink' OR sc.color='blue' 1 ELSE 0 END) >0
AND
HAVING SUM(CASE WHEN sc.color='yellow' 1 ELSE 0 END) = 0
HAVING is applied to grouped results
if sum of valid colors is >0 that means one of the 3 valid colors exists for the shape
if sum of invalid color is >0 thah means yellow color exist
So you get shapes where one (or more) of valid colors exists and invalid color does not exist
UPDATE:
SELECT s.id
FROM shape s INNER JOIN shape_color sc ON s.id=sc.id
GROUP BY s.id
HAVING
SUM(CASE WHEN sc.color='red' OR sc.color='pink' OR sc.color='blue' OR sc.color='yellow' 1 ELSE 0 END) >0
AND
SUM(CASE WHEN sc.color='red' OR sc.color='pink' OR sc.color='blue' OR sc.color='yellow' 1 ELSE 0 END) <=3
Assuming the colors are independent, you can do:
SELECT sc.shape_id
FROM shape_color sc join
color c
ON sc.color_id = c.color_id
WHERE c.color in ('red', 'pink', 'blue', 'yellow')
GROUP BY sc.shape_id
HAVING COUNT(*) < 4;
(Your column names aren't clear but you should get the idea.)
By looking in shape_color, you are eliminating the first condition -- a color is needed. This then just checks that there are fewer than 4 colors. Implicitly, there is at least one, but you could add HAVING COUNT(*) > 0 AND COUNT(*) < 4.
If you find the solution with GROUP BY and HAVING could be confusing, simple first concatenate the colors in a string using LISTAGG.
Note that an INNER JOIN is used eliminate the shapes without colors (here 4 - see sample data below).
Also the WHERE predicate limits only the relevant colors.
select s.shape_id,
LISTAGG(c.color, ',') WITHIN GROUP (ORDER BY c.color) color_lst
from shape s
join shape_color c
on s.shape_id = c.shape_id
where c.color in ('red', 'pink', 'blue', 'yellow')
group by s.shape_id
;
SHAPE_ID COLOR_LST
---------- ---------------------------
1 blue,pink,red,yellow
2 red
3 blue,pink,yellow
You task is than as simple as eliminate the only negative case of all four colors:
with colors as (
select s.shape_id,
LISTAGG(c.color, ',') WITHIN GROUP (ORDER BY c.color) color_lst
from shape s
join shape_color c
on s.shape_id = c.shape_id
where c.color in ('red', 'pink', 'blue', 'yellow')
group by s.shape_id
)
select shape_id
from colors
where color_lst != 'blue,pink,red,yellow'
SHAPE_ID
----------
2
3
You shoud take some care to check, that the colors within a shape are unique. If not you must add a subquery that distincts the colors within shape. The same is valid also for the HAVING based solutions.
Sample Data
create table shape as
select 1 shape_id from dual union all
select 2 shape_id from dual union all
select 3 shape_id from dual union all
select 4 shape_id from dual;
create table shape_color as
select 1 shape_id, 'red' color from dual union all
select 1 shape_id, 'pink' color from dual union all
select 1 shape_id, 'blue' color from dual union all
select 1 shape_id, 'yellow' color from dual union all
select 2 shape_id, 'red' color from dual union all
select 3 shape_id, 'pink' color from dual union all
select 3 shape_id, 'blue' color from dual union all
select 3 shape_id, 'yellow' color from dual;

How to SELECT COUNT multiple values in one column

rather a newbie at SQL, so please be gentle....as I think this is a basic one.
I'm trying to write a query with multiple (13) counts, based off Column1. The 1st Count is the over-all total. And then the 12 others are filtered by Color. I can get my results by doing multiple Counts all in one query, but this gives me 13 rows of data. The goal here is to get everything on just one row. So, almost like each count would be its own column. Here is an example of the data model
Database = CARS, Table = TYPES, Column1 = LICENSE, Column2 = COLOR
SELECT COUNT (LICENSE) AS 'Total ALL Cars'
FROM CARS.TYPES WITH (NOLOCK)
SELECT COUNT (LICENSE) AS 'Total RED Cars'
FROM CARS.TYPES WITH (NOLOCK)
WHERE COLOR = 'RED'
And on & on & on for each remaining color. This works, but again, I'm trying to streamline it all into one row of data, IF possible. Thank you in advance
You simply need to include color in select statement and group by it to count cars of each color.
SELECT Color, Count(*)
FROM CARS.TYPES WITH(NOLOCK)
GROUP BY Color
or
SELECT COUNT(CASE WHEN Color = 'RED' THEN 1
ELSE NULL
END) AS RedCars
,COUNT(CASE WHEN Color = 'BLUE' THEN 1
ELSE NULL
END) AS BlueCars
,COUNT(*) AS AllCars
FROM CARS.TYPES WITH ( NOLOCK )
You can do this with a conditional SUM():
SELECT SUM(CASE WHEN Color = 'Red' THEN 1 END) AS 'Total Red Cars'
,SUM(CASE WHEN Color = 'Blue' THEN 1 END) AS 'Total Blue Cars'
FROM CARS.TYPES
If using MySQL you can simplify further:
SELECT SUM(Color = 'Red') AS 'Total Red Cars'
,SUM(Color = 'Blue') AS 'Total Blue Cars'
FROM CARS.TYPES
Or with PIVOT
SELECT RED + BLUE + GREEN AS total,
RED,
BLUE,
GREEN
FROM CARS.TYPES PIVOT (COUNT (LICENSE) FOR COLOR IN ([RED], [BLUE], [GREEN])) P
SELECT SUM(Al) AllCount, SUM(Red) RedCount, SUM(Green) GreenCount, ...
(
SELECT 1 AS Al
, CASE WHEN Color = 'Red' THEN 1 ELSE 0 END AS Red
, CASE WHEN Color = 'Green' THEN 1 ELSE 0 END AS Green
...
FROM CARS.Types
)

SQL display summation of data in row

I have a table like this
No.
--
b
r
g
g
r
b
r
g
I want resultset like below
Type of color | Ocurrence
Blue 2
green 3
red 3
TOTAL 8
Please help
Sounds like CASE and GROUP BY would be what you need;
SELECT
CASE WHEN color = 'r' THEN 'red'
WHEN color = 'g' THEN 'green'
WHEN color = 'b' THEN 'blue'
END "Type of color", COUNT(color) "Occurrence"
FROM Table1
GROUP BY color
ORDER BY color;
An SQLfiddle to test with.
To get a total, one (not necessarily the simplest) way is to just UNION with the total;
WITH cte AS (
SELECT
CASE WHEN color = 'r' THEN 'red'
WHEN color = 'g' THEN 'green'
WHEN color = 'b' THEN 'blue'
END "Type of color", COUNT(color) "Occurrence"
FROM Table1
GROUP BY color
UNION
SELECT 'TOTAL',COUNT(*)
FROM Table1
)
SELECT * FROM cte
ORDER BY CASE WHEN "Type of color" = 'TOTAL' THEN 1 END;
Another SQLfiddle.
Joachim's answer is fine, except there is an easier way to get the total using rollup:
SELECT
CASE WHEN color = 'r' THEN 'red'
WHEN color = 'g' THEN 'green'
WHEN color = 'b' THEN 'blue'
when color is NULL then 'Total'
END "Type of color", COUNT(*) "Occurrence"
FROM Table1
GROUP BY color with rollup
ORDER BY (case when color is null then 1 else 0 end), color

Select records based on column priority

First of all, the title of this question is horrible, but I didn't find a better way to describe my issue.
There's probably a very easy way to do this, but I couldn't figure it out. This is very similar to this question, but I'm running on sqlite3 (iOS) so I suspect my options are much more limited.
I have a table with product records. All records have an ID (note: I'm not talking about the row ID, but rather an identification number unique to each product). Some products may have two entries in the table (both with the same ID). The only difference would be in a special column (let's say column COLOUR can be either RED or GREEN).
What I want to do is create a list of unique products based on the value of COLOUR, with priority to GREEN if both GREEN and RED records exist for the same product.
In short, if I have the following case:
id PRODUCT ID COLOUR
1 1001 GREEN
2 1002 GREEN
3 1002 RED
4 1003 RED
I would like my SELECT to return the rows 1, 2 and 4. How can I achieve this?
My current approach is to have separate tables, and do the join manually, but obviously this is a very bad idea..
Note: I've tried to use the same approach from here:
SELECT *
FROM xx
WHERE f_COLOUR = "GREEN"
UNION ALL
SELECT *
FROM xx
WHERE id not in (SELECT distinct id
FROM xx
WHERE f_COLOUR = "GREEN");
But the result I'm getting is rows 1,2,3,4 instead of just 1,2,4. What am I missing?
Edit: One more question please: how can this be made to work with a subset of records, ie. if instead of the entire table I wanted to filter some records?
For example, if I had something like SELECT * FROM table WHERE productID LIKE "1%" ... how can I retrieve each unique product, but still respecting the colour priority (GREEN>RED)?
Your query is nearly correct. Just use PRODUCTID and not ID.
SELECT *
FROM xx
WHERE f_COLOUR = "GREEN"
UNION
SELECT *
FROM xx
WHERE PRODUCTID not in
(SELECT PRODUCTID
FROM xx
WHERE f_COLOUR = "GREEN");
SQLFiddle Demo
Try this
SELECT *
FROM xx
WHERE COLOUR = 'GREEN'
UNION
SELECT *
FROM xx WHERE P_Id not in
(SELECT P_Id
FROM Persons
WHERE COLOUR = 'GREEN');
See ALSO SQL FIDDLE DEMO
I just want to offer that you can do this with a group by:
select (case when sum(case when colour = 'Green' then 1 else 0 end) > 0
then max(case when colour = 'Green' then id end)
else max(case when colour = 'Red' then id end)
end) as id,
product_id
(case when sum(case when colour = 'Green' then 1 else 0 end) > 0 then 'Green'
else 'Red'
end) as colour
from t
group by product_id
You can have it like this
WITH PriorityTable
AS
(
SELECT T.*,
ROW_NUMBER() OVER (PARTITION BY T.ID
ORDER BY PT.ColorPriority ) PriorityColumn
FROM XX AS T
INNER JOIN (
SELECT 'RED' AS f_COLOUR , 1 AS ColorPriority
UNION
SELECT 'GREEN' AS f_COLOUR , 2 AS ColorPriority
) AS PT
ON T.f_COLOUR = PT.f_COLOUR
)
SELECT * FROM PriorityTable
WHERE PriorityColumn = 1