How to SELECT COUNT multiple values in one column - sql

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
)

Related

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;

Merging tables into New table while retaining information

I apologize in advance as the title is not very descriptive.
I have approximately 40+ tables each with the same exact table layout columns, and data save for one column. I would like to take that column which is not the same across all the tables and merge them into one table. Confusing? Let me illustrate..
SRCTbl01:
ID TYPE COLR1 INSTOCK
-----------------------
1 B RED YES
2 B BLUE YES
3 P GREEN NO
4 B BLACK YES
SRCTbl02:
ID TYPE COLR1 INSTOCK
-----------------------
1 B RED YES
2 B BLUE NO
3 P GREEN YES
4 B BLACK YES
SRCTbl03:
ID TYPE COLR1 INSTOCK
-----------------------
1 B RED YES
2 B BLUE NO
3 P GREEN NO
4 B BLACK NO
RESULT: (Type P to be excluded)
ID TYPE COLR1 SRCTbl01 SRCTbl02 SRCTbl03
----------------------------------------------
1 B RED YES YES YES
2 B BLUE YES NO NO
4 B BLACK YES YES NO
And finally after all that I'd like to make the table look something like this:
INSTOCK Table:
Customer RED BLUE BLACK
---------------------------
SRCTbl1 YES YES YES
SRCTbl2 YES NO YES
SRCTbl3 YES NO NO
I'm not entirely sure whether I can directly manipulate the tables into looking like the final iteration so I thought I should ask how to get it to the first Result as to me it seems simpler.
Thank you for the help, I've spent a full 8 hours on this and have yet to find a way to achieve it so I have come here to ask the experts.
EDIT: To clarify, I have had zero success in achieving the results I illustrated above. I have tried using SELECT .. Union SELECT, and FULL JOINS.
Using this code resulted in duplicates ( I was trying to just get the INSTOCK)
SELECT 01.INSTOCK, 02.INSTOCK, 03.INSTOCK
FROM dbo.SRCTbl01 AS 01, dbo.SRCTbl02 AS 02, dbo.SRCTbl03 AS 03
WHERE 01.TYPE='B'
I tried very many but this is probably the closest I got.
you could do something like that, all in one :
You first flatten with union, then take the max 'instock' for each color by customer (MAX will work as 'YES' > 'NO')
select Customer, MAX(RED) as RED, MAX(BLUE) as BLUE, MAX(BLACK) as BLACK
FROM(
SELECT 'SRCTbl01' as Customer,
CASE WHEN COLR1 = 'RED' then INSTOCK ELSE 'NO' END as RED,
CASE WHEN COLR1 = 'BLUE' then INSTOCK ELSE 'NO' END as BLUE,
CASE WHEN COLR1 = 'BLACK' then INSTOCK ELSE 'NO' END as BLACK
FROM SRCTbl01
WHERE Type <> 'P'
UNION
SELECT 'SRCTbl02' as Customer,
CASE WHEN COLR1 = 'RED' then INSTOCK ELSE 'NO' END as RED,
CASE WHEN COLR1 = 'BLUE' then INSTOCK ELSE 'NO' END as BLUE,
CASE WHEN COLR1 = 'BLACK' then INSTOCK ELSE 'NO' END as BLACK
FROM SRCTbl02
WHERE Type <> 'P'
UNION
SELECT 'SRCTbl03' as Customer,
CASE WHEN COLR1 = 'RED' then INSTOCK ELSE 'NO' END as RED,
CASE WHEN COLR1 = 'BLUE' then INSTOCK ELSE 'NO' END as BLUE,
CASE WHEN COLR1 = 'BLACK' then INSTOCK ELSE 'NO' END as BLACK
FROM SRCTbl03
WHERE Type <> 'P'
) as a
GROUP BY Customer
(You just need to add a CREATE TABLE INSTOCK as <codegiven>)
see SqlFiddle
Using UNION and PIVOT, something like this should do what you want (PIVOT should work on SQL Server 2005 and newer):
SELECT Customer, [Red], [Blue], [Black]
FROM (
SELECT 'SRCTbl01' AS Customer, COLR1, INSTOCK FROM SRCTbl01 WHERE Type <> 'P'
UNION
SELECT 'SRCTbl02' AS Customer, COLR1, INSTOCK FROM SRCTbl02 WHERE Type <> 'P'
UNION
SELECT 'SRCTbl03' AS Customer, COLR1, INSTOCK FROM SRCTbl03 WHERE Type <> 'P'
/* UNION ... */
) AS SRC
PIVOT (
MAX(INSTOCK)
FOR COLR1 IN ([Red], [Blue], [Black])
) AS pvt

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

Return 4 separate counts for single column in SSRS DataSet

I want to provide 5 counts to SSRS from a conditional count on a column. For instance, suppose the column held the color of a product -- green ,blue, red and yellow. What I would like to do is return the count of each in a single query.
Although I can accomplish getting this done using a case statement:
Select
COUNT(*) 'Count',
case
When Color = 'BL' then 'Blue
When Color = 'RD' then 'Red
When Color = 'YL' then 'Yellow
When Color = 'GR' then 'Green
Else 'All Others'
End as Payment
From COLORS(NoLock)
Group by
case
When Color = 'BL' then 'Blue
When Color = 'RD' then 'Red
When Color = 'YL' then 'Yellow
When Color = 'GRthen ‘Green’
Else 'All Others'
End
When I use the dataset is SSRS, all I get is the a single count. I don't want to create 4 dataset queries as I'm actually selection the records by the parameters start and end date and I would end up having 5 sets of date parameters.
This should do the trick
select count (*) as Total,
sum (case when color='BL' then 1 else 0 end) as BlueTotal,
sum (case when color='RD' then 1 else 0 end) as RedTotal,
sum (case when color='YL' then 1 else 0 end) as YellowTotal,
sum (case when color='GR' then 1 else 0 end) as GreenTotal
from Colors

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