SQL - Pivot tables with 3 cross tabs - sql-server-2008-r2

I have the raw data looks like
Class Cert Name Benefit Coverage
-------------------------------
1 1001 ABC EHC Family
1 1001 ABC DEN Family
2 1002 XYZ EHC Single
2 1002 XYZ DEN Single
3 1003 LMN EHC Couple
3 1003 LMN DEN Couple.
I want the final output to look like
**Class** **Benefit**
EHC-Single EHC-Couple EHC-Family DEN-Single DEN-Couple DEN-Family
1 1 1
2 1 1
3 1 1
Values below the columns are count of Certificates.

yes you can do it like below. See in SQL Fiddle
;WITH CTE
AS (SELECT COUNT(*) Counts,
Class,
Benefit + '-' + Coverage AS [Benefits]
FROM ##MyTemp
GROUP BY Class,
Benefit,
Coverage)
SELECT Class,
[EHC-Single],
[EHC-Couple],
[EHC-Family],
[DEN-Single],
[DEN-Couple],
[DEN-Family]
FROM CTE
PIVOT(MAX(Counts)
FOR [Benefits] IN ([EHC-Single],
[EHC-Couple],
[EHC-Family],
[DEN-Single],
[DEN-Couple],
[DEN-Family])) AS TempList;

Related

T-SQL: split string on multiple delimiters

I have been given a T-SQL task: to convert/format names which are in ALL CAPS into Title Case. I have decided that splitting the names into tokens, and capitalizing the first letter out of each token, would be a reasonable approach (I am willing to take advice if there's a better option, especially in T-SQL).
That said, to accomplish this, I'd have to split the name fields on spaces AND dashes, hyphens, etc. Then, once it is tokenized, I can worry about normalizing the case.
Is there any reasonable way to split a string along any delimiter in a list?
If ease & performance is important then grab a copy of PatExtract8k.
Here's a basic example where I split on any character that is not a letter or number ([^a-z0-9]):
-- Sample String
DECLARE #string VARCHAR(8000) = 'abc.123&xyz!4445556__5566^rrr';
-- Basic Use
SELECT pe.* FROM samd.patExtract8K(#string,'[^a-z0-9]') AS pe;
Output:
itemNumber itemIndex itemLength item
--------------- ----------- ----------- -------------
1 1 3 abc
2 5 3 123
3 9 3 xyz
4 13 7 4445556
5 22 4 5566
6 27 3 rrr
It returns what you need as well as:
the length of the item (ItemLength)
It's position in the string (ItemIndex)
It's ordinal position in the string (ItemNumber.)
Now against a table. Here we're doing the same thing but I'll explicitly call out the characters I want to use as a delimiter. Here it's any of these characters: *.&,?%/>
-- Sample Table
DECLARE #table TABLE (SomeId INT IDENTITY, SomeString VARCHAR(100));
INSERT #table VALUES('abc***332211,,XXX'),('abc.123&&555%jjj'),('ll/111>ff?12345');
SELECT t.*, pe.*
FROM #table AS t
CROSS APPLY samd.patExtract8K(t.SomeString,'[*.&,?%/>]') AS pe;
This returns:
SomeId SomeString itemNumber itemIndex itemLength item
----------- ------------------- ------------ ---------- ----------- ---------
1 abc***332211,,XXX 1 1 3 abc
1 abc***332211,,XXX 2 7 6 332211
1 abc***332211,,XXX 3 15 3 XXX
2 abc.123&&555%jjj 1 1 3 abc
2 abc.123&&555%jjj 2 5 3 123
2 abc.123&&555%jjj 3 10 3 555
2 abc.123&&555%jjj 4 14 3 jjj
3 ll/111>ff?12345 1 1 2 ll
3 ll/111>ff?12345 2 4 3 111
3 ll/111>ff?12345 3 8 2 ff
3 ll/111>ff?12345 4 11 5 12345
On the other hand - If I wanted to extract the delimiters I could change the pattern like this: [^*.&,?%/>]. Now the same query returns:
SomeId itemNumber itemIndex itemLength item
----------- -------------------- -------------------- ----------- ---------
1 1 4 3 ***
1 2 13 2 ,,
2 1 4 1 .
2 2 8 2 &&
2 3 13 1 %
3 1 3 1 /
3 2 7 1 >
3 3 10 1 ?

Replace empty strings with NULL instead of empty strings when using JOIN

I have two tables:
table_a
id name
1 john
2 dave
3 tim
4 marta
5 jim
table_b
id sum random_metric
1 10.50 abc
3 11.5 efg
5 5.76 ghj
I have joined them on id
SELECT ...
FROM table_a
LEFT JOIN table_b ON table_a.id = table_b.id
and I get:
id name sum random_metric
1 john 10.5 abc
2 dave
3 tim 11.5 efg
4 marta
5 jim 5.76 ghj
Then I want to convert the sum column to double precision but since it has empty strings in rows 2, 4 it does not work.
How could I join tables so that I would have this:
id name sum random_metric
1 john 10.5 abc
2 dave NULL NULL
3 tim 11.5 efg
4 marta NULL NULL
5 jim 5.76 ghj

select all columns with suffix _test in q kdb

I have a partitioned table, similar to below table:
q)t:([]date:3#2019.01.01; a:1 2 3; a_test:2 3 4; b_test:3 4 5; c: 6 7 8);
date a a_test b_test c
----------------------------
2019.01.01 1 2 3 6
2019.01.01 2 3 4 7
2019.01.01 3 4 5 8
Now, I want to fetch date column and all columns have names with suffix "_test" from table t.
Expected output:
date a_test b_test
------------------------
2019.01.01 2 3
2019.01.01 3 4
2019.01.01 4 5
In my original table, there are more than 100 columns with name having _test so below is not a practical solution in this case.
q)select date, a_test, b_test from t where date=2019.01.01
I tried various options like below, but of no use:
q)delete all except date, *_test from select from t where date=2019.01.01
If the columns you are selecting are variable then you should use a functional qSQL statement to perform the query. The following can be used in your case
q)query:{[tab;dt;c]?[tab;enlist (=;`date;dt);0b;(`date,c)!`date,c]}
q)query[t;2019.01.01;cols[t] where cols[t] like "*_*"]
date a_test b_test
------------------------
2019.01.01 2 3
2019.01.01 3 4
2019.01.01 4 5
In order to craft a particular functional statement, you can parse your query, putting dummy columns in place if you aren't sure what they should be
q)parse "select date,c1,c2 from tab where date=dt"
?
`tab
,,(=;`date;`dt)
0b
`date`c1`c2!`date`c1`c2
A functional select is probably the best way to go here if you require adding further filters.
?[`t;();0b;{x!x}`date,exec c from meta t where c like "*_test"]
The functional form of any select quesry can be obtained by using the -5! operator on any SQL style statement.
In the example below I have created a table with 20 fields, each one beginning with either a or b.
I then use the functional form to define which fields I want.
q)tab:{[x] enlist x!count[x]#0}`$"_" sv ' raze string `a`b,/:\:til 10
q){[t;s]?[t;();0b;{[x] x!x} cols[t] where cols[t] like s]}[tab;"b*"]
b_0 b_1 b_2 b_3 b_4 b_5 b_6 b_7 b_8 b_9
---------------------------------------
0 0 0 0 0 0 0 0 0 0
q){[t;s]?[t;();0b;{[x] x!x} cols[t] where cols[t] like s]}[tab;"a*"]
a_0 a_1 a_2 a_3 a_4 a_5 a_6 a_7 a_8 a_9
---------------------------------------
0 0 0 0 0 0 0 0 0 0
q)-5!" select a,b from c"
?
`c
()
0b
`a`b!`a`b
Alternatively, if I don't require any filtering I can use the # operator as in below:
{[x;s] (cols[x] where cols[x] like s)#x}[ tab;"a*"]

query multiple attribute in a table with single attribute in another table

I can't explain my problem in English well. So I write my problem in a personal way.
user_id name surname
1 john great
2 mary white
3 joseph alann
event_id official_id assistant_id date
1 1 2 2017-12-19
2 1 3 2017-12-20
3 2 3 2017-12-21
I want to get names at the same time when I query an event. I tried:
SELECT * FROM event a, user b WHERE a.official_id=b.user_id AND a.assistant_id=b.user_id
When I use "OR" instead of "AND" gives me cartesian result. I want the result like:
event_id off_id off_name asst_id asst_name date
1 1 john 2 mary 2017-12-19
2 1 john 3 joseph 2017-12-20
3 2 mary 3 joseph 2017-12-21

nber of rows within a group in oracle

In order to generate a report in ireport i need this query in oracle 10g.
SCHOOL:
SELECT STID,NAME,DEPT,SUM(CHARGE)
STID | PROG | DEPT | CHARGE
1 1 A 1
2 1 B 2
3 2 A 2
4 2 B 1
5 1 A 2
Desired OUTPUT:
DEPT | PROG | NBER_OF_STID | TOT_CHG
A 1 2 3
2 1 2
B 1 1 2
2 1 1
this is my query
SELECT DISTINCT DEPT, DISTINCT PROG, COUNT(STID), SUM (CHARGE) TOT_CHG
FROM SCHOOL
GROUP BY DEPT, PROG, STID, CHARGE
Help Thanks.
You need to group by only the columns that aren't going to be aggregated.
Try this:
SELECT DEPT, PROG, COUNT(STID) NBER_OF_STID, SUM (CHARGE) TOT_CHG
FROM SCHOOL
GROUP BY DEPT, PROG
Note: in your query you'll always get a tabular view, so results will be like this:
DEPT | PROG | NBER_OF_STID | TOT_CHG
A 1 2 3
A 2 1 2
B 1 1 2
B 2 1 1
IMHO, the visual formatting should be made in the report itself (ireport)