Create Multiple row from single row - sql

I have data from 1 table with single row data
link : https://www.dropbox.com/s/86j2o9jo9v8vqip/stack1.PNG?dl=0
Function dateMarine NumberMarine dateBOC NumberBOC Status
------------------------------------------------------------------------------
Shipping 2000/01/01 10 2007/01/01 11 Paid
And I want to create multiple row from single row data 1 shipmentNumber , like this
Function No.Doc date status
--------------------------------------
Shipping 10 2000/01/01 Paid
Shipping 11 2007/01/01 Paid
How to create query for this case, I have some reference like this:
SELECT [Date]
, API
, LEFT(col,CHARINDEX('_',col)-1)'Latency'
, RIGHT(col,CHARINDEX('_',REVERSE(col))-1)'Aggregation'
, Value
FROM
(
SELECT [Date],API,col,value
FROM Table1
CROSS APPLY
(
VALUES ('Latency1_Avg', [Latency1_Avg]),('Latency1_Min', [Latency1_Min]),('Latency1_Max', [Latency1_Max]),('Latency2_Avg', [Latency2_Avg]),('Latency2_Min', [Latency2_Min]),('Latency2_Max', [Latency2_Max])
) C (COL, VALUE)
) SRC
But i think my case is different
sorry i use the link to show picture of my case, because i cant import pic in my stackoverflow account
Thankyou for youre helping me

Related

Exclude entire group when one condition matches

Let's say I have a table like such:
Store productId
Test 1 6524
Test 1 6521
Test 1 6523
Test 2 6234
Test 2 6264
Test 3 6395
I am trying to find a way to check whether the store has the product 6524 and if it does it should remove the entire group (store) from the list so that the result can look like the below.
Expected Outcome:
Test 2
Test 3
I have tried doing a GROUP by followed by HAVING productId <> 6524 but this of course just gets rid of the single row not the entire group.
You can use NOT EXISTS such as
SELECT DISTINCT Store
FROM tab t
WHERE NOT EXISTS ( SELECT 0
FROM tab
WHERE Store = t.Store
AND productId = 6524 )
which filters out the matching values of Store column
select store
from your_table
group by store
having sum(productId=6524)=0;

Return 0 if no row found in SQL Server using Pivot

Thanks everyone, and thank you #Aaron Bertrand, your answer solved my problem :) !
i am struggling to find a solution to my problem, here is my query in SQL Server :
EDIT: a little more details : this is the kind of data that a have in my table :
identifier
date
status
1
20220421
have a book
2
20220421
have a pdf
3
20220421
have a pdf
4
20220421
have a book
5
20220421
have a book
6
20220421
have a book
my query gives this result :
have a book
have a pdf
4
2
so in the case when there is no records for a date, I need a query that returns :
have a book
have a pdf
0
0
instead of :
have a book
have a pdf
SELECT * FROM
(
Select status from database.dbo.MyTable where date = '20220421' and status
in ('have a book','have a pdf')) y
PIVOT( Count (status) FOR y.status IN ( [have a book],[have a
pdf])
) pivot_table
This query works well but my issue is that i want to display 0 in the results if no row is found, i tried with IsNull, it works without the Pivot part, but i wasn't able to make it work with the Pivot.
Thanks in advance :)
Since we're only dealing with bits and one or zero rows for a given date, you can just add a union to include a second row with zeros, and take the max (which will either pull the 0 or 1 from the real row, or the zeros from the dummy row when a real row doesn't exist).
SELECT [have a book] = MAX([have a book]),
[have a pdf] = MAX([have a pdf])
FROM
(
SELECT [have a book], [have a pdf] FROM
(
SELECT status FROM dbo.whatever
WHERE date = '20220421'
AND status IN ('have a book','have a pdf')
) AS src PIVOT
(
COUNT(status) FOR status IN
([have a book],[have a pdf])
) AS pivot_table
UNION ALL SELECT 0,0
) AS final;
Example db<>fiddle

SQL Rows to Columns if column values are unknown

I have a table that has demographic information about a set of users which looks like this:
User_id Category IsMember
1 College 1
1 Married 0
1 Employed 1
1 Has_Kids 1
2 College 0
2 Married 1
2 Employed 1
3 College 0
3 Employed 0
The result set I want is a table that looks like this:
User_Id|College|Married|Employed|Has_Kids
1 1 0 1 1
2 0 1 1 0
3 0 0 0 0
In other words, the table indicates the presence or absence of a category for each user. Sometimes the user will have a category where the value if false, sometimes the user will have no row for a category, in which case IsMember is assumed to be false.
Also, from time to time additional categories will be added to the data set, and I'm wondering if its possible to do this query without knowing up front all the possible category names, in other words, I won't be able to specify all the column names I want to count in the result. (Note only user 1 has category "has_kids" and user 3 is missing a row for category "married"
(using Postgres)
Thanks.
You can use jsonb funcions.
with titles as (
select jsonb_object_agg(Category, Category) as titles,
jsonb_object_agg(Category, -1) as defaults
from demog
),
the_rows as (
select null::bigint as id, titles as data
from titles
union
select User_id, defaults || jsonb_object_agg(Category, IsMember)
from demog, titles
group by User_id, defaults
)
select id, string_agg(value, '|' order by key)
from (
select id, key, value
from the_rows, jsonb_each_text(data)
) x
group by id
order by id nulls first
You can see a running example in http://rextester.com/QEGT70842
You can replace -1 with 0 for the default value and '|' with ',' for the separator.
You can install tablefunc module and use the crosstab function.
https://www.postgresql.org/docs/9.1/static/tablefunc.html
I found a Postgres function script called colpivot here which does the trick. Ran the script to create the function, then created the table in one statement:
select colpivot ('_pivoted', 'select * from user_categories', array['user_id'],
array ['category'], '#.is_member', null);

SQL Select using distinct and Cast [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
SQL Select DISTINCT using CAST
Let me try this one more time... I'm not a sql guy so please bear with me as I try to explain this... I have a table called t_recordkeepingleg with three columns of data. Column1 is named LEGTRIPNUMBER that happens to be a string that starts with the letter Q followed by 4 numbers. I need to strip off the Q and convert the remaining 4 characters (numbers) to an integer. Everyone with me so far? Column2 of this table is named LEGDATE. Column3 is named LEGGROUP.
Here's the input scenario
LEGTRIPNUMBER LEGDATE LEGGROUP
Q1001 08/12/12 0001
Q1001 09/15/12 0002
Q1002 09/01/12 0001
Q1002 09/08/12 0003
Q1002 09/09/12 0002
As you can see the input table has rows where LEGTRIPNUMBER occurs more than once. I only want the first occurrence.
This is my current select statement - it works but returns all rows.
SELECT *,
CAST(
substring("t_RecordkeepingLeg"."LEGTRIPNUMBER",2,4) as INT
) as Num_Trip_Num
FROM "1669"."dbo"."t_RecordkeepingLeg" "t_RecordkeepingLeg"
Where left "t_RecordkeepingLeg"."LEGTRIPNUMBER",1) = 'Q'
I want to modify this so that it only selects ONE occurance of the Qnnnn. When the row gets selected I want to have LEGDATE and LEGGROUP available to me. How do I do this?
Thank you,
Can it be as simple as below? I've just added condiotion on leggroup being 0001
SELECT *,
CAST(substring("t_RecordkeepingLeg"."LEGTRIPNUMBER",2,4) as INT) as Num_Trip_Num
FROM "1669"."dbo"."t_RecordkeepingLeg" "t_RecordkeepingLeg"
Where left ("t_RecordkeepingLeg"."LEGTRIPNUMBER",1) = 'Q'
and "t_RecordkeepingLeg"."LEGGROUP"='0001'
If you have a unique primay key in your table you can do something like the below;
SELECT CAST(
substring("t_RecordkeepingLeg"."LEGTRIPNUMBER",2,4) as INT
) as Num_Trip_Num
FROM "1669"."dbo"."t_RecordkeepingLeg" "t_RecordkeepingLeg"
Where "t_RecordkeepingLeg"."ID" In(
Select Min("t_RecordkeepingLeg"."ID")
From "1669"."dbo"."t_RecordkeepingLeg" "t_RecordkeepingLeg"
Where left ("t_RecordkeepingLeg"."LEGTRIPNUMBER",1) = 'Q'
Group By "t_RecordkeepingLeg"."LEGTRIPNUMBER"
)
Which values of LEGDATE & LEGGROUP do you want for the distinct LEGTRIPNUMBER? there are multiple non-distinct possibilities and the concept of "first occurrence" is only valid with an explicit order.
To get the values where LEGDATE is the earliest for example;
select Num_Trip_Num, LEGDATE, LEGGROUP from (
select
cast(substring(t_RecordkeepingLeg.LEGTRIPNUMBER, 2, 4) as INT) as Num_Trip_Num,
row_number() over (partition by substring(t_RecordkeepingLeg.LEGTRIPNUMBER, 2, 4) order by t_RecordkeepingLeg.LEGDATE asc) as row,
t_RecordkeepingLeg.LEGDATE,
t_RecordkeepingLeg.LEGGROUP
from t_RecordkeepingLeg
where left (t_RecordkeepingLeg.LEGTRIPNUMBER, 1) = 'Q'
) T
where row = 1

List category/subcategory tree and display its sub-categories in the same row

I have a hierarchical table of Regions and sub-regions, and I need to list a tree of regions and sub-regions (which is easy), but also, I need a column that displays, for each region, all the ids of it's sub regions.
For example:
id name superiorId
-------------------------------
1 RJ NULL
2 Tijuca 1
3 Leblon 1
4 Gavea 2
5 Humaita 2
6 Barra 4
I need the result to be something like:
id name superiorId sub-regions
-----------------------------------------
1 RJ NULL 2,3,4,5,6
2 Tijuca 1 4,5,6
3 Leblon 1 null
4 Gavea 2 4
5 Humaita 2 null
6 Barra 4 null
I have done that by creating a function that retrieves a STUFF() of a region row,
but when I'm selecting all regions from a country, for example, the query becomes really, really slow, since I execute the function to get the region sons for each region.
Does anybody know how to get that in an optimized way?
The function that "retrieves all the ids as a row" is:
I meant that the function returns all the sub-region's ids as a string, separated by a comma.
The function is:
CREATE FUNCTION getSubRegions (#RegionId int)
RETURNS TABLE
AS
RETURN(
select stuff((SELECT CAST( wine_reg.wine_reg_id as varchar)+','
from (select wine_reg_id
, wine_reg_name
, wine_region_superior
from wine_region as t1
where wine_region_superior = #RegionId
or exists
( select *
from wine_region as t2
where wine_reg_id = t1.wine_region_superior
and (
wine_region_superior = #RegionId
)
) ) wine_reg
ORDER BY wine_reg.wine_reg_name ASC for XML path('')),1,0,'')as Sons)
GO
When we used to make these concatenated lists in the database we took a similar approach to what you are doing at first
then when we looked for speed
we made them into CLR functions
http://msdn.microsoft.com/en-US/library/a8s4s5dz(v=VS.90).aspx
and now our database is only responsible for storing and retrieving data
this sort of thing will be in our data layer in the application