PIvoting table around date column in Mysql - mysql

I am trying to pivot this table
timetableId, assignmentId, dateChecked, hoursWorked
1, 11, 2017-09-10, 5
2, 12, 2017-09-10, 5
3, 13, 2017-09-11, 8
4, 11, 2017-09-11, 8
5, 12, 2017-09-11, 8
6, 13, 2017-09-10, 8
so that it would show
assignmentId, tenth, eleventh
11, 5, 8
12, 5, 8
13, 0, 8
I have the following code based on the tutorial from this website http://stratosprovatopoulos.com/web-development/mysql/pivot-a-table-in-mysql/
create view timetable_extended as (
select
timetables.assignmentId,
case when dateChecked = '10-09-2017' then timetables.hoursWorked end as tenth,
case when dateChecked = '11-09-2017' then timetables.hoursWorked end as eleventh
from timetables
);
create view timetable_extended_Pivot as (
select
assignmentId,
sum(tenth) as tenth,
sum(eleventh) as eleventh
from timetable_extended
group by assignmentId
);
create view timetable_extended_Pivot_Pretty as (
select
assignmentId,
coalesce(tenth, 0) as tenth,
coalesce(eleventh, 0) as eleventh
from timetable_extended_Pivot
);
however for some reason the first view returns all values as null instead of doing what it is supposed to do - namely this
assignmentId, tenth, eleventh
11, 5, NULL
11, NULL 8
12, 5, NULL
12, NULL 8
13, NULL, 8
What am I doing wrong? Do I need to convert the date to a string?
I have tried the same code with string as the main column and it works perfectly
create table User_Items
(
Cust_Names varchar(10),
Item_Type varchar(50),
Item_Amount float
);
insert into User_Items values
('Alison', 'Computer', 345.39),
('Alison', 'Monitor', 123.45),
('Jason', 'Computer', 435.34),
('Jason', 'Monitor', 158.23),
('Jason', 'Software', 243.54);
create view User_Items_Extended as (
select
User_Items.Cust_Names,
case when Item_Type = "Computer" then Item_Amount end as Computer,
case when Item_Type = "Monitor" then Item_Amount end as Monitor,
case when Item_Type = "Software" then Item_Amount end as Software
from User_Items
);
create view User_Items_Extended_Pivot as (
select
Cust_Names,
sum(Computer) as Computer,
sum(Monitor) as Monitor,
sum(Software) as Software
from User_Items_Extended
group by Cust_Names
);
create view User_Items_Extended_Pivot_Pretty as (
select
Cust_Names,
coalesce(Computer, 0) as Computer,
coalesce(Monitor, 0) as Monitor,
coalesce(Software, 0) as Software
from User_Items_Extended_Pivot
);

The problem is here:
case when dateChecked = '10-09-2017'
Use YYYY-MM-DD format for your date comparisons, not MM-DD-YYYY.

Related

I need to perform a query in MySQL that joins two queries that I performed in just one query

I need to perform a MySQL query that returns the number of projects (COD_PROJETO) and adds the total subscription value (VALOR_TOTAL_ASSIN), per subscriber (COD_SUBSCRIBE) all in the same query.
I can make these queries separately, as shown below, but I need them in the same query.
QUANTITY OF PROJECTS:
SELECT COUNT(COD_PROJETO) AS QTD_PROJETOS
FROM DIM_PROJETOS ;
TOTAL AMOUNT PER SUBSCRIBER:
SELECT COD_ASSINANTE,SUM(VALOR_TOTAL_ASSIN) AS VLR_TOT
FROM TAB_ASSINATURAS
GROUP BY COD_ASSINANTE;
I need the above two results, in the same query.
Also follows the creation of tables with the data inserted:
CREATE TABLE DIM_PROJETOS(COD_PROJETO INT, REVISTA VARCHAR(100), EDITORA VARCHAR(3), TIPO_REVISTA VARCHAR(50));
CREATE TABLE TAB_ASSINATURAS(COD_ASSINANTE INT, COD_PROJETO INT, VIGENCIA INT, QT_PARCELAS INT, VALOR_TOTAL_ASSIN FLOAT);
INSERT INTO DIM_PROJETOS VALUES(837, "MINHA CASA", "EDA", "IMPRESSA");
INSERT INTO DIM_PROJETOS VALUES(838, "MAXIMA", "CAR", "IMPRESSA");
INSERT INTO DIM_PROJETOS VALUES(847, "ELLE DIGITAL", "EDA", "DIGITAL");
INSERT INTO DIM_PROJETOS VALUES(873, "CLAUDIA DIGITAL", "EDA", "DIGITAL");
INSERT INTO DIM_PROJETOS VALUES(883, "VEJA DIGITAL + ONLINE", "EDA", "DIGITAL");
INSERT INTO DIM_PROJETOS VALUES(884, "QUADRINHOS DISNEY", "EDA", "IMPRESSA");
INSERT INTO TAB_ASSINATURAS VALUES(1001, 837, 13, 1, 145.60);
INSERT INTO TAB_ASSINATURAS VALUES(1001, 901, 6, 1, 58.98);
INSERT INTO TAB_ASSINATURAS VALUES(1001, 907, 42, 12, 315);
INSERT INTO TAB_ASSINATURAS VALUES(1002, 847, 28, 1,373.40 );
INSERT INTO TAB_ASSINATURAS VALUES(1002, 873, 12, 12, 133.20);
INSERT INTO TAB_ASSINATURAS VALUES(1002, 893, 12, 1, 86.72);
INSERT INTO TAB_ASSINATURAS VALUES(1003, 905, 36, 18, 508.67);
INSERT INTO TAB_ASSINATURAS VALUES(1004, 901, 36, 18, 216);
Below is an image of the tables(Note, they have no relationship.):
Just cross join the two queries.
SELECT *
FROM (
SELECT COUNT(COD_PROJETO) AS QTD_PROJETOS
FROM DIM_PROJETOS
) AS q1
CROSS JOIN (
SELECT COD_ASSINANTE,SUM(VALOR_TOTAL_ASSIN) AS VLR_TOT
FROM TAB_ASSINATURAS
GROUP BY COD_ASSINANTE
) AS q2

MYSQL-how to insert geometry data

I'm trying to insert geometry data using MYSQL, here is a code-example:
CREATE TABLE CARTESIAN
(
ROW_ID INT NOT NULL,
G GEOMETRY,
PRIMARY KEY(ROW_ID)
)
INSERT INTO CARTESIAN
VALUES (0,'POINT(1 1)'),
(1,'LINESTRING(2 1, 6 6)'),
(2,'POLYGON((0 5, 2 5, 2 7, 0 7, 0 5))')
When I run the INSERT I receive the message "Cannot get geometry object from data you send to the GEOMETRY field".
Can you explain me where I'm wrong?
You need to convert the text representations into GEOMETRY before you can insert them using the ST_GeomFromText function. Try this:
CREATE TABLE CARTESIAN
(
ROW_ID INT NOT NULL,
G GEOMETRY,
PRIMARY KEY(ROW_ID)
);
INSERT INTO CARTESIAN
VALUES (0,ST_GeomFromText('POINT(1 1)')),
(1,ST_GeomFromText('LINESTRING(2 1, 6 6)')),
(2,ST_GeomFromText('POLYGON((0 5, 2 5, 2 7, 0 7, 0 5))'));
SELECT * FROM CARTESIAN
Output:
ROW_ID G
0 [GEOMETRY - 25 B]
1 [GEOMETRY - 45 B]
2 [GEOMETRY - 97 B]

SQL: value higher than percentage of population of values

I wish to calculate the value which is higher than a percentage of the population of values, this per group.
Suppose I have:
CREATE TABLE project
(
id int,
event int,
val int
);
INSERT INTO project(id,event,val)
VALUES
(1, 11, 43),
(1, 12, 19),
(1, 13, 19),
(1, 14, 53),
(1, 15, 45),
(1, 16, 35),
(2, 21, 22),
(2, 22, 30),
(2, 23, 25),
(2, 24, 28);
I now want to calculate for each id what is the val that will be for example higher than 5%, or 30% of the val for that id.
For example, for id=1, we have the following values: 43, 19, 19, 53, 45, 35.
So the contingency table would look like this:
19 35 43 45 53
2 1 1 1 1
and the val=20 (higher than 19) would be chosen to be higher than 5% (actuall 2 out of 6) of the rows.
The contengency table for id 2 is:
22 25 28 30
1 1 1 1
My expected out is:
id val_5p_coverage val_50p_coverage
1 20 36
2 23 26
val_5p_coverage is the value val needed to be above at least 5% of val in the id.
val_50p_coverage is the value val needed to be above at least 50% of val in the id.
How can I calculate this with SQL ?
I managed to do it in HiveQL (for Hadoop) as follows:
create table prep as
select *,
CUME_DIST() OVER(PARTITION BY id ORDER BY val ASC) as proportion_val_equal_or_lower
from project
SELECT id,
MIN(IF(proportion_val_equal_or_lower>=0.05, val, NULL)) AS val_5p_coverage,
MIN(IF(proportion_val_equal_or_lower>=0.50, val, NULL)) AS val_50p_coverage
FROM prep
GROUP BY id
Although this is not MySQL nor SQL per se, it might help to do it in MySQL or SQL.

SQL Server Tree Query

I need some help is MS SQL Server Query. I’m not much of a DBA. I have an application with an Organization Table which is made up of a parent-child relationship:
CREATE TABLE [dbo].[Organizations](
[OrgPK] [int] IDENTITY(1,1) NOT NULL,
[OrgParentFK] [int] NULL,
[OrgName] [varchar](200) NOT NULL,
CONSTRAINT [PK__Organizations] PRIMARY KEY CLUSTERED
Sample data looks like this:
OrgPK, OrgParentFK, OrgName
1, 0, Corporate
2, 1, Department A
3, 1, Department B
4, 2, Division 1
5, 2, Division 2
6, 3, Division 1
7, 6, Section 1
8, 6, Section 2
I'm trying to generate a query that returns an org path based on a given OrgPK. Example if given OrgPK = 7 the query would return 'Corporation/Department B/Division 1/Section 1'
If give OrgPk = 5 the return string would be 'Corporation/Department A/Division 2'
Thank you for your assistance.
WITH OrganizationsH (OrgParentFK, OrgPK, OrgName, level, Label) AS
(
SELECT OrgParentFK, OrgPK, OrgName, 0, CAST(OrgName AS VARCHAR(MAX)) As Label
FROM Organizations
WHERE OrgParentFK IS NULL
UNION ALL
SELECT o.OrgParentFK, o.OrgPK, o.OrgName, level + 1, CAST(h.Label + '/' + o.OrgName VARCHAR(MAX)) As Label
FROM Organizations o JOIN OrganizationsH h ON o.OrgParentFK = h.OrgPK
)
SELECT OrgParentFK, OrgPK, OrgName, level, Label
FROM OrganizationsH
WHERE OrgPK = 5
h/t to marc_s
It can also be solved by creating a scalar valued function:
-- SELECT [dbo].[ListTree](5)
CREATE FUNCTION [dbo].[ListTree](#OrgPK int)
RETURNS varchar(max)
AS
BEGIN
declare #Tree varchar(MAX)
set #Tree = ''
while(exists(select * from dbo.Organizations where OrgPK=#OrgPK))
begin
select #Tree=OrgName+'/'+#Tree,
#OrgPK=OrgParentFK
from dbo.Organizations
where OrgPK=#OrgPK
end
return left(#Tree,len(#Tree)-1)
END

Select Parent node in nested data set

Have teh follwoing query which is fine and dandy...
SELECT
`node`.`site_pages_id` AS `page_id` ,
GROUP_CONCAT(`parent`.`site_pages_id` SEPARATOR '/') AS `path` ,
IFNULL( CONCAT( '/' , GROUP_CONCAT(`parent`.`url` SEPARATOR '/') ) , '/' ) AS `url`
FROM
`site_pages` AS `node`
LEFT JOIN
`site_pages` AS `parent`
ON
`node`.`lft_limit` BETWEEN `parent`.`lft_limit` AND `parent`.`rgt_limit`
GROUP BY
`node`.`site_pages_id`
ORDER BY
`node`.`lft_limit` ASC
produces the following
1, 1, /
2, 1/2, /about-us
8, 1/2/8, /about-us/meet-the-team
3, 1/3, /web
5, 1/5, /print
6, 1/6, /branding
7, 1/7, /contact-us
All sweet.
I'd like to select the immediate parent and just the immediate parent for each node.
My feeble attempts at doing so without a nasty subquery fail misearably (not much better with TBO).
Tips muchly appreciated
No probs Martin...
page_id url lft_limit rgt_limit
1, NULL, 1, 14,
2, about-us, 2, 5,
3, web, 6, 7,
5, print, 8, 9,
6, branding, 10, 11,
7, contact-us, 12, 13,
8, meet-the-team, 3, 4,