tsql newbie here.
I have a table, similar to this one:
CarId CarName UserId RentedTimes CrashedTimes
`````````````````````````````````````````````````````````
1 Ferrari 1 2 0
2 DB9 1 5 0
3 Ferrari 2 4 0
4 Audi 3 1 0
5 Audi 1 1 0
Assuming the table is called 'Cars', I am trying to select total number of times each of cars were rented. According to the table above, Ferrari was rented total of 6 times, DB9 five times and Audi twice.
I tried doing this:
select CarName, SUM(RentedTimes)
from Cars
group by CarName, RentedTimes
order by RentedTimes desc
but, it is returning two rows of ferrari with 2,4 as rented times and so on..
How do I select all cars, and total times each were rented, please?
Thanks
Edited the query to include sort order, sorry.
select CarName, SUM(RentedTimes)
from Cars
group by CarName
ORDER BY SUM(RentedTimes) DESC
Try this way.. removed RentedTimes from group by
Related
I have two tables department and category.In my query result listing same department multiple times.I want to group departments based on category table priority column.
Eg Data:
id dept_name dept_category priority
1 Cardio category 2 2
2 Ortho category 3 3
3 Ortho category 1 1
4 ENT category 1 1
5 Ortho category 2 2
I wannt the reslt like:
id dept_name dept_category priority
1 Cardio category 2 2
3 Ortho category 1 1
4 ENT category 1 1
How can i fetch the resul like this.In my category table cantain priority 1,2,3 then 1 is highest priority.I need to group department based on highest priority.
We can use DISTINCT ON with Postgres:
SELECT DISTINCT ON (dept_name) *
FROM yourTable
ORDER BY dept_name, priority;
I have data with teacher and student scores (on a scale 1-5). I want to show how many teacher grades were 1, 2, 3, 4, 5 and same with the students grading themselves.
I have the data in 2 formats, in the same row, and pivoted on 2 seperate rows. ie
Same row like this
student name | Teacher Score | Student Score
----------------------------------------------------
Jack 4 3
Jim 2 3
Tom 5 4
Pivoted like this
student name | Pivot Field | Score
-----------------------------------------------------
Jack student score 3
Jack teacher score 4
Jim student score 2
Jim teacher score 3
Tom student score 4
Tom teacher score 5
I'm just looking to do this in tableau, count how many of each grading scores were casted by teachers, and students, like this
ALL 5 SCORES | TOTAL COUNT TEACHER | TOTAL COUNT STUDENT
1 0 0 (zero 1's were given out)
2 1 0
3 0 2 (ie both Jack and Jim gave themselves a 3)
4 1 1
5 1 0
Does that make sense? Please let me know if I need to further explain. I feel like I should know this but I'm stumped and I'm having trouble putting the right words together to search for it.. thank you in advance!
Try creating a bin field of your scores. Right click on you score field and select create then select bins. In the size of bins box change it to 1. Then add the new field to your columns and number of records to rows.
Let's ignore the database design - https://stackoverflow.com/questions/41180638/sql-replacing-an-array-column-of-ids-with-an-array-of-the-records. I'm more just curious if this is possible. I have a table called orders with a column of products. In this column is an array with the ids of all the products that are in the order. Is it possible for me to query for the products and replace the products column with the result? This is what I have so far, but errors for having too many columns on the subquery.
SELECT o.*, ( SELECT p.* FROM products p WHERE p.id = ANY(o.products::int[])) products FROM orders o
Order's Table:
ID Products Status Total
1 [1,2,5] 1 4
2 [1,3,5] 1 5
3 [1,3,6] 1 5
Products Table:
ID Name Price
1 Blue shoe 1
2 Red Shoe 1
3 Green Shoes 2
4 Purple Shoe 1
5 Orange Shoes 2
6 Pink Shoes 2
Desired Output - selecting the first order.
{
ID:1,
Products:[ <Products Record-1>, <Products Record-2>, <Products Record-5>
],
Status: 1,
Total: 4
}
I have several CTEs. CTE1A counts number of type A shops in area 1. CTE1B counts number of type B shops in area 1 and so on up to CTE1D. Similarly, CTE2B counts number of type B shops in area 2 and so on. shop_types CTE selects all types of shops: A,B,C,D. How to display a table that shows for each area (column) how many shops of each type there is (rows).
For example:
1 2 3 4 5
A 0 7 4 0 0
B 2 3 8 2 9
C 8 5 8 1 6
D 7 1 5 4 3
Database has 2 tables:
Table regions: shop_id, region_id
Table shops: shop_id, shop_type
WITH
shop_types AS (SELECT DISTINCT shops.shop_type AS type FROM shops WHERE shops.shop_type!='-9999' AND shops.shop_type!='Other'),
cte1A AS (
SELECT regions.region_id, COUNT(regions.shop_id) AS shops_number, shops.shop_type
FROM regions
RIGHT JOIN shops
ON shops.shop_id=regions.shop_id
WHERE regions.region_id=1
AND shops.shop_type='A'
GROUP BY shops.shop_type,regions.region_id)
SELECT * FROM cte1A
I'm not entirely sure I understand why you are after, but it seems you are looking for something like this:
select sh.shop_type,
count(case when r.region_id = 1 then 1 end) as region_1_count,
count(case when r.region_id = 2 then 1 end) as region_2_count,
count(case when r.region_id = 3 then 1 end) as region_3_count
from shops sh
left join regions r on r.shop_id = sh.shop_id
group by sh.shop_type
order by sh.shop_type;
You need to add one case statement for each region you want to have in the output.
If you are using Postgres 9.4 you can replace the case statements using a filter condition which kind of makes the intention a bit easier to understand (I think)
count(*) filter (where r.region_id = 1) as region_1_count,
count(*) filter (where r.region_id = 2) as region_2_count,
...
SQLFiddle: http://sqlfiddle.com/#!1/98391/1
And before you ask: no you can't make the number of columns "dynamic" based on a select statement. The column list for a query must be defined before the statement is actually executed.
I have a hard time figuring this one out. And i apologize if the answer is out there, i have searched through all of stackoverflow.
I have an order system, where i order by tableID, and continue to make rows in my Database if someone orders stuff. My problem is getting my data out on 1 row, in this example the table ID, so all the ordered stuff, shows on 1 line only.
I have 3 tables, Food, Drink, Dessert, all with a foreign key in my OrderTable.
id fk_tableid fk_drinkId fk_foodId fk_dessId amount
1 5 2 0 0 2
2 5 0 1 0 1
3 5 0 2 0 1
4 5 0 0 2 2
11 8 1 0 0 2
21 1 1 0 0 5
22 1 0 1 0 9
23 1 0 0 1 2
By a normal select, with left joins, i can get the data out on multiple rows, like this where i get those with tableId 5 and showing the name of the ordered consumable also:
id fk_tableId fk_drinkId fk_foodId fk_dessId amount foodName drinkName dessertName
1 5 2 0 0 2 NULL Sodavand NULL
2 5 0 1 0 1 Lasagne NULL NULL
3 5 0 2 0 1 Pizza NULL NULL
4 5 0 0 2 2 NULL NULL Softice
I tried using group_concat also, which put data on 1 line, but it seems to put everything on 1 line, not just grouped by tableId.
How i want it to be is something like this (the 2x Lasagne for example, is just how i want it to look at the site, but maybe i need to use 1xLasagne twice instead. It would just look messy with 1x Beer 10 times.):
fk_tableId fk_drinkId fk_foodId fk_dessId foodName drinkName dessertName fulllPrice
5 2,2 1,2 2,2 Pizza,Lasagne 2xSodavand 2xSoftice 195
I am aware my question might be wrongly formatted, but i also have a hard time 100% knowing what to google and search for here. I have tried for 2 days, and even asked my teacher who could not do it, he was doing something with CASES and sum(), but it did not work out either.
Any help will be much appreciated!
UPDATE:
Added SQL Query:
SELECT
menukort_ordre.id,
fk_tableId,
fk_drinkId,
fk_foodId,
fk_dessId,
amount,
menukort_food.name AS foodName,
menukort_drink.name AS drinkName,
menukort_dessert.name AS dessertName
FROM menukort_ordre
LEFT Join menukort_drink
ON (menukort_ordre.fk_drinkId = menukort_drink.id)
LEFT Join menukort_food
ON (menukort_ordre.fk_foodId = menukort_food.id)
LEFT Join menukort_dessert
ON (menukort_ordre.fk_dessId = menukort_dessert.id)
WHERE fk_tableid = fk_tableid
With GROUP_CONCAT i tried to do this instead, which put it on 1 row, but due to my WHERE, i get all data on 1 row.
GROUP_CONCAT(menukort_food.name ) AS foodName,
GROUP_CONCAT(menukort_drink.name) AS drinkName,
GROUP_CONCAT(menukort_dessert.name) AS dessertName
UPDATE:
First off I changed your database design since there was no need for 3 tables like that unless you really wanted them to be separated as such. I understand wanting to separate data, but there are times to do so and times not to do it. I understand since my personal database project has me breaking everything up. So the below solution will be based off of my design which is as follows.
Category
Code or ID (PK)
Category
This table will be a lookup table just to make sure drink and food and desert is spelled correctly. Frankly you don't need it unless you need that information specific and want it to be correct.
Next will be the table that stores the drinks, deserts, and food
Items
ID serial
Category
Name
Price
and final the order table that will keep track of the orders
Order
BillID
TableNum
ItemNum (fk)
ID (PK)
This way you can keep track of which table the food goes to and each check or bill. Your design was fine if you wanted to find out how much each table made in a day, but I'm assuming like an actual restaurant you would want to know for each bill. With this you can have multiple orders of a coke or whatever at the same table on the same bill.
Now on to the solution.
This doesn't have the count, but could work on it if you really need it, but frankly I think it is pointless to have a count unless you are going to ungroup the results and have something like this:
tableNum BillNum ItemNum ItemName
1 1 1 Coke
1 1 2 Steak
1 1 3 Pasta
1 1 1 Coke
then you could end up with something like this
tableNum BillNum ItemNum ItemName TimesBy
1 1 1 Coke 2
1 1 2 Steak 1
1 1 3 Pasta 1
The SQL CODE below will give you what you need I believe. I'm using my version of the database and I think you should too just because it is easier and there is no point to having 3 tables for each thing.
CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (
select BillID, tablenum,ItemNum,Items.name,Items.price
from Orders, Items
where Orders.ItemNum=Items.id
);
create TEMPORARY TABLE IF NOT EXISTS table3 AS (
select SUM(price) as total, BillID
from table2
group by BillID
);
select table3.BillID, TableNum, GROUP_CONCAT(ItemNum order by ItemNum ASC) as ItemNum, GROUP_CONCAT(name order by name ASC) as Item, GROUP_CONCAT(price order by name asc) as ItemPrice, total
from table2, table3
where table2.BillID=table3.BillID
group by BillID;
DROP TABLE IF EXISTS table2;
DROP TABLE IF EXISTS table3;
A few other solutions would be to look into using something like php (programming) to help with this or a stored procedure.
If you need an explanation just ask. Also I'm curious is this for homework or a project? I just want to know why your doing this?
Hope it helps.